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 napi_create_async_work(env, nullptr, resourceName, ExecuteWork, WorkComplete, callbackData, 40 &callbackData->work); 41 42 // Add the asynchronous work object to the asynchronous task queue. 43 napi_queue_async_work(env, callbackData->work); 44 return nullptr; 45 } 46 ``` 47 482. Call **ExecuteWork** in a worker thread to execute the thread-safe function. 49 ```c++ 50 static void ExecuteWork(napi_env env, void *data) 51 { 52 CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); 53 std::promise<std::string> promise; 54 auto future = promise.get_future(); 55 napi_call_threadsafe_function(callbackData->tsfn, &promise, napi_tsfn_nonblocking); 56 try { 57 auto result = future.get(); 58 // OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", result.c_str()); 59 } catch (const std::exception &e) { 60 // OH_LOG_INFO(LOG_APP, "XXX, Result from JS %{public}s", e.what()); 61 } 62 } 63 ``` 64 653. Execute the asynchronous callback in a JS thread. 66 ```c++ 67 static napi_value ResolvedCallback(napi_env env, napi_callback_info info) 68 { 69 void *data = nullptr; 70 size_t argc = 1; 71 napi_value argv[1]; 72 if (napi_get_cb_info(env, info, &argc, argv, nullptr, &data) != napi_ok) { 73 return nullptr; 74 } 75 size_t result = 0; 76 char buf[32] = {0}; 77 napi_get_value_string_utf8(env, argv[0], buf, 32, &result); 78 reinterpret_cast<std::promise<std::string> *>(data)->set_value(std::string(buf)); 79 return nullptr; 80 } 81 82 static napi_value RejectedCallback(napi_env env, napi_callback_info info) 83 { 84 void *data = nullptr; 85 if (napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &data) != napi_ok) { 86 return nullptr; 87 } 88 reinterpret_cast<std::promise<std::string> *>(data)->set_exception( 89 std::make_exception_ptr(std::runtime_error("Error in jsCallback"))); 90 return nullptr; 91 } 92 93 static void CallJs(napi_env env, napi_value jsCb, void *context, void *data) 94 { 95 if (env == nullptr) { 96 return; 97 } 98 napi_value undefined = nullptr; 99 napi_value promise = nullptr; 100 napi_get_undefined(env, &undefined); 101 napi_call_function(env, undefined, jsCb, 0, nullptr, &promise); 102 napi_value thenFunc = nullptr; 103 if (napi_get_named_property(env, promise, "then", &thenFunc) != napi_ok) { 104 return; 105 } 106 napi_value resolvedCallback; 107 napi_value rejectedCallback; 108 napi_create_function(env, "resolvedCallback", NAPI_AUTO_LENGTH, ResolvedCallback, data, 109 &resolvedCallback); 110 napi_create_function(env, "rejectedCallback", NAPI_AUTO_LENGTH, RejectedCallback, data, 111 &rejectedCallback); 112 napi_value argv[2] = {resolvedCallback, rejectedCallback}; 113 napi_call_function(env, promise, thenFunc, 2, argv, nullptr); 114 } 115 ``` 116 1174. After the task is complete, clear and reclaim resources. 118 ```c++ 119 static void WorkComplete(napi_env env, napi_status status, void *data) 120 { 121 CallbackData *callbackData = reinterpret_cast<CallbackData *>(data); 122 napi_release_threadsafe_function(callbackData->tsfn, napi_tsfn_release); 123 napi_delete_async_work(env, callbackData->work); 124 callbackData->tsfn = nullptr; 125 callbackData->work = nullptr; 126 } 127 ``` 128 1295. Initialize the module and call the API from ArkTS. 130 ``` 131 // Initialize the module. 132 static napi_value Init(napi_env env, napi_value exports) { 133 CallbackData *callbackData = new CallbackData(); // Release when the thread exits. 134 napi_property_descriptor desc[] = { 135 {"startThread", nullptr, StartThread, nullptr, nullptr, nullptr, napi_default, callbackData}, 136 }; 137 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 138 return exports; 139 } 140 141 // Call the API of ArkTS. 142 import nativeModule from'libentry.so'; // Import native capabilities. 143 144 let callback = (): Promise<string> => { 145 return new Promise((resolve) => { 146 setTimeout(() => { 147 resolve("string from promise"); 148 }, 5000); 149 }); 150 } 151 nativeModule.startThread(callback); 152 ``` 153