1# Thread Safety Development Using Node-API 2 3 4## When to Use 5 6**napi_create_threadsafe_function** is a Node-API interface used to create a thread-safe JS function, which can be called from multiple threads without race conditions or deadlocks. Thread-safe functions can be used in the following scenarios: 7 8 9- Asynchronous computing: If a time-consuming computing or I/O operation needs to be performed, you can create a thread-safe function to have the computing or I/O operation executed in a dedicated thread. This ensures normal running of the main thread and improves the response speed of your application. 10 11- Data sharing: When multiple threads need to access the same data, using a thread-safe function can prevent race conditions or deadlocks during data read and write operations. 12 13- Multithread programming: In the case of multithread programming, a thread-safe function can ensure communication and synchronization between multiple threads. 14 15 16## Example 17 181. Define a thread-safe function at the native entry. 19 ```c++ 20 struct CallbackData { 21 napi_threadsafe_function tsfn; 22 napi_async_work work; 23 }; 24 25 static napi_value StartThread(napi_env env, napi_callback_info info) 26 { 27 size_t argc = 1; 28 napi_value jsCb = nullptr; 29 CallbackData *callbackData = nullptr; 30 napi_get_cb_info(env, info, &argc, &jsCb, nullptr, reinterpret_cast<void **>(&callbackData)); 31 32 // Create a thread-safe function. 33 napi_value resourceName = nullptr; 34 napi_create_string_utf8(env, "Thread-safe Function Demo", NAPI_AUTO_LENGTH, &resourceName); 35 napi_create_threadsafe_function(env, jsCb, nullptr, resourceName, 0, 1, callbackData, nullptr, 36 callbackData, CallJs, &callbackData->tsfn); 37 38 // Create an asynchronous work object. 39 // ExecuteWork is executed on a non-JS thread created by libuv. The napi_create_async_work is used to simulate the scenario, in which napi_call_threadsafe_function is used to submit tasks to a JS thread from a non-JS thread. 40 napi_create_async_work(env, nullptr, resourceName, ExecuteWork, WorkComplete, callbackData, 41 &callbackData->work); 42 43 // Add the asynchronous work object to the asynchronous task queue. 44 napi_queue_async_work(env, callbackData->work); 45 return nullptr; 46 } 47 ``` 48 492. Call **ExecuteWork** in a worker thread to execute the thread-safe function. 50 ```c++ 51 static void ExecuteWork(napi_env env, void *data) 52 { 53 CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); 54 std::promise<std::string> promise; 55 auto future = promise.get_future(); 56 napi_call_threadsafe_function(callbackData->tsfn, &promise, napi_tsfn_nonblocking); 57 try { 58 auto result = future.get(); 59 // OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", result.c_str()); 60 } catch (const std::exception &e) { 61 // OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", e.what()); 62 } 63 } 64 ``` 65 663. Execute the asynchronous callback in a JS thread. 67 ```c++ 68 static napi_value ResolvedCallback(napi_env env, napi_callback_info info) 69 { 70 void *data = nullptr; 71 size_t argc = 1; 72 napi_value argv[1]; 73 if (napi_get_cb_info(env, info, &argc, argv, nullptr, &data) != napi_ok) { 74 return nullptr; 75 } 76 size_t result = 0; 77 char buf[32] = {0}; 78 napi_get_value_string_utf8(env, argv[0], buf, 32, &result); 79 reinterpret_cast<std::promise<std::string> *>(data)->set_value(std::string(buf)); 80 return nullptr; 81 } 82 83 static napi_value RejectedCallback(napi_env env, napi_callback_info info) 84 { 85 void *data = nullptr; 86 if (napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &data) != napi_ok) { 87 return nullptr; 88 } 89 reinterpret_cast<std::promise<std::string> *>(data)->set_exception( 90 std::make_exception_ptr(std::runtime_error("Error in jsCallback"))); 91 return nullptr; 92 } 93 94 static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) 95 { 96 if (env == nullptr) { 97 return; 98 } 99 napi_value undefined = nullptr; 100 napi_value promise = nullptr; 101 napi_get_undefined(env, &undefined); 102 napi_call_function(env, undefined, jsCb, 0, nullptr, &promise); 103 napi_value thenFunc = nullptr; 104 if (napi_get_named_property(env, promise, "then", &thenFunc) != napi_ok) { 105 return; 106 } 107 napi_value resolvedCallback; 108 napi_value rejectedCallback; 109 napi_create_function(env, "resolvedCallback", NAPI_AUTO_LENGTH, ResolvedCallback, data, 110 &resolvedCallback); 111 napi_create_function(env, "rejectedCallback", NAPI_AUTO_LENGTH, RejectedCallback, data, 112 &rejectedCallback); 113 napi_value argv[2] = {resolvedCallback, rejectedCallback}; 114 napi_call_function(env, promise, thenFunc, 2, argv, nullptr); 115 } 116 ``` 117 1184. After the task is complete, clear and reclaim resources. 119 ```c++ 120 static void WorkComplete(napi_env env, napi_status status, void *data) 121 { 122 CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); 123 napi_release_threadsafe_function(callbackData->tsfn, napi_tsfn_release); 124 napi_delete_async_work(env, callbackData->work); 125 callbackData->tsfn = nullptr; 126 callbackData->work = nullptr; 127 } 128 ``` 129 1305. Initialize the module and call the API from ArkTS. 131 ```c++ 132 // Initialize the module. 133 static napi_value Init(napi_env env, napi_value exports) { 134 CallbackData *callbackData = new CallbackData(); // Release when the thread exits. 135 napi_property_descriptor desc[] = { 136 {"startThread", nullptr, StartThread, nullptr, nullptr, nullptr, napi_default, callbackData}, 137 }; 138 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 139 return exports; 140 } 141 142 // Call the API of ArkTS. 143 import nativeModule from 'libentry.so'; // Import native capabilities. 144 145 let callback = (): Promise<string> => { 146 return new Promise((resolve) => { 147 setTimeout(() => { 148 resolve("string from promise"); 149 }, 5000); 150 }); 151 } 152 nativeModule.startThread(callback); 153 ``` 154