Skip to content

Commit

Permalink
fix: Use thread_local storage to increment getCurrentThreadId() (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
mrousavy committed Apr 17, 2024
1 parent 84861e8 commit e704b03
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 10 deletions.
14 changes: 7 additions & 7 deletions cpp/WKTJsiWorkletApi.h
Expand Up @@ -3,7 +3,6 @@
#include <jsi/jsi.h>

#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
Expand Down Expand Up @@ -109,13 +108,14 @@ class JsiWorkletApi : public JsiHostObject {
"deprecated in favor of context.createRunAsync(..) or "
"context.runAsync(..) - please migrate to the new API!");
}

JSI_HOST_FUNCTION(getCurrentThreadId) {
std::thread::id threadId = std::this_thread::get_id();
std::stringstream stream;
stream << threadId;
std::string string = stream.str();
return jsi::String::createFromUtf8(runtime, string);
static int threadCounter = 0;
static thread_local int thisThreadId = -1;
if (thisThreadId == -1) {
thisThreadId = threadCounter++;
}
return jsi::Value(thisThreadId);
}

JSI_HOST_FUNCTION(__jsi_is_array) {
Expand Down
2 changes: 1 addition & 1 deletion example/Tests/worklet-tests.ts
Expand Up @@ -121,7 +121,7 @@ export const worklet_tests = {
},
check_thread_id_exists: () => {
const threadId = Worklets.getCurrentThreadId();
return ExpectValue(threadId.length > 0, true);
return ExpectValue(Number.isSafeInteger(threadId), true);
},
check_thread_id_consecutive_calls_are_equal: () => {
const first = Worklets.getCurrentThreadId();
Expand Down
7 changes: 5 additions & 2 deletions src/types.ts
Expand Up @@ -146,9 +146,12 @@ export interface IWorkletNativeApi {
runOnJS: <T>(func: () => T) => Promise<T>;

/**
* Returns the current C++ Thread ID this method was called on.
* Returns a unique identifier for the Thread this method is called on.
*
* Thread-IDs start at 0 and use `thread_local` storage to store their IDs
* which are incremented everytime a new Thread calls `getCurrentThreadId()`.
*/
getCurrentThreadId(): string;
getCurrentThreadId(): number;
/**
* Get the default Worklet context.
*/
Expand Down

0 comments on commit e704b03

Please sign in to comment.