```
struct MyContext {
std::string importantString;
};
// Thread-safe JavaScript function object.
napi_threadsafe_function g_threadsafeFunction;
static void CallbackFunction(napi_env env, napi_value jsCallback, void *context, void *data)
{
size_t argc = 1;
napi_value argv[1];
int* aa = static_cast<int*>(data);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "THREAD SAFE", "Native CallbackFunction *data: %{public}d", *aa);
MyContext* myContext = static_cast<MyContext*>(context);
napi_create_string_utf8(env, myContext->importantString.c_str(), NAPI_AUTO_LENGTH, &argv[0]);
// Execute the callback function in a JavaScript environment. After the data is callbacked to JS, it will not wait for JS to finish executing.
napi_call_function(env, nullptr, jsCallback, argc, argv, nullptr);
}
static void FinalizeFunction(napi_env env, void* data, void* hint)
{
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "THREAD SAFE", "Native FinalizeFunction called.");
MyContext* myContext = static_cast<MyContext*>(data);
delete myContext;
}
static void ThreadFunction(void *data)
{
// Asynchronously call a JavaScript function in another thread.
std::this_thread::sleep_for(std::chrono::seconds(1));
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "THREAD SAFE", "Native another thread sleep 1s.");
// Invoke a JavaScript function asynchronously from a native thread. After this, it will execute CallbackFunction to callback data to js.
int *param = new int(10);
napi_call_threadsafe_function(g_threadsafeFunction, param, napi_tsfn_nonblocking);
// Decrement the reference count of a threadsafe function, potentially destroying it. After this, it will execute FinalizeFunction to release data.
napi_release_threadsafe_function(g_threadsafeFunction, napi_tsfn_release);
}
napi_value StartThreadsafefunc(napi_env env, napi_callback_info info)
{
size_t argc = 1;
napi_value args[1];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
MyContext* context = new MyContext{"Hello from C++"};
napi_value name;
napi_create_string_utf8(env, "testThreadsafefunc", NAPI_AUTO_LENGTH, &name);
// Create a thread-safe function that can be called from worker threads.
napi_create_threadsafe_function(env, args[0], nullptr, name, 0, 1,
context, FinalizeFunction, context, CallbackFunction, &g_threadsafeFunction);
// Start a new thread.
std::thread newThread(ThreadFunction, nullptr);
newThread.join();
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DOMAIN, "THREAD SAFE", "Native main thread.");
return nullptr;
}
```
```
testNapi.startThreadsafefunc((res: string) => {
console.log('THREAD SAFE console callback res is :', res);
})
```
4. 运行后,执行结果如下:
```
A00000/THREAD SAFE com.examp...lication I Native another thread sleep 1s.
A00000/THREAD SAFE com.examp...lication I Native main thread.
A00000/THREAD SAFE com.examp...lication I Native CallbackFunction *data: 10
A03d00/JSAPP com.examp...lication I THREAD SAFE js callback res is : Hello from C++
A00000/THREAD SAFE com.examp...lication I Native FinalizeFunction called.
```