1# 使用扩展的Node-API接口在异步线程中运行和停止事件循环 2<!--Kit: NDK--> 3<!--Subsystem: arkcompiler--> 4<!--Owner: @xliu-huanwei; @shilei123; @huanghello--> 5<!--Designer: @shilei123--> 6<!--Tester: @kirl75; @zsw_zhushiwei--> 7<!--Adviser: @fang-jinxu--> 8 9## 场景介绍 10开发者在自己创建的ArkTS运行环境中调用异步的ArkTS接口时,可以通过使用Node-API中的扩展接口napi_run_event_loop和napi_stop_event_loop来运行和停止ArkTS实例中的事件循环。 11 12## 调用异步的ArkTS接口示例 13调用的ArkTS接口为异步接口时,需要通过扩展接口napi_run_event_loop将异步线程中的事件循环运行起来,底层事件队列中的异步任务将被处理执行。当前Node-API扩展了两种事件循环模式来运行异步线程的事件循环,分别为napi_event_mode_nowait模式和napi_event_mode_default模式。 14如果使用napi_event_mode_nowait模式运行底层事件循环,系统会尝试从底层的事件队列中取出一个任务并处理,完成之后事件循环停止,如果底层的事件队列中没有任务,事件循环会立刻停止,当前的异步线程不会被阻塞; 15如果使用napi_event_mode_default模式来运行底层事件循环,系统会阻塞当前的线程,同时会一直尝试从事件队列中获取任务并执行处理这些任务。如果不想当前线程继续被阻塞,可以使用扩展接口napi_stop_event_loop将正在运行的事件循环停止。 16 17### 示例代码 18- 模块注册 19 ```c++ 20 // napi_init.cpp 21 #include "napi/native_api.h" 22 #include <napi/common.h> 23 #include <pthread.h> 24 25 static napi_value ResolvedCallback(napi_env env, napi_callback_info info) 26 { 27 napi_stop_event_loop(env); 28 return nullptr; 29 } 30 31 static napi_value RejectedCallback(napi_env env, napi_callback_info info) 32 { 33 napi_stop_event_loop(env); 34 return nullptr; 35 } 36 37 static void *RunEventLoopFunc(void *arg) 38 { 39 // 1. 创建ArkTS实例 40 napi_env env; 41 napi_status ret = napi_create_ark_runtime(&env); 42 if (ret != napi_ok) { 43 return nullptr; 44 } 45 46 // 2. 加载自定义的模块 47 napi_value objectUtils; 48 // 'com.example.myapplication' 为当前应用的bundleName 49 ret = napi_load_module_with_info(env, "entry/src/main/ets/pages/ObjectUtils", "com.example.myapplication/entry", &objectUtils); 50 if (ret != napi_ok) { 51 return nullptr; 52 } 53 54 // 3. 调用异步SetTimeout接口 55 napi_value setTimeout = nullptr; 56 napi_value promise = nullptr; 57 58 napi_get_named_property(env, objectUtils, "SetTimeout", &setTimeout); 59 napi_call_function(env, objectUtils, setTimeout, 0, nullptr, &promise); 60 61 napi_value theFunc = nullptr; 62 if (napi_get_named_property(env, promise, "then", &theFunc) != napi_ok) { 63 return nullptr; 64 } 65 66 napi_value resolvedCallback = nullptr; 67 napi_value rejectedCallback = nullptr; 68 napi_create_function(env, "resolvedCallback", NAPI_AUTO_LENGTH, ResolvedCallback, nullptr, &resolvedCallback); 69 napi_create_function(env, "rejectedCallback", NAPI_AUTO_LENGTH, RejectedCallback, nullptr, &rejectedCallback); 70 napi_value argv[2] = {resolvedCallback, rejectedCallback}; 71 napi_call_function(env, promise, theFunc, 2, argv, nullptr); 72 73 auto flag = reinterpret_cast<bool *>(arg); 74 if (*flag == true) { 75 napi_run_event_loop(env, napi_event_mode_default); 76 } else { 77 // 非阻塞式的处理任务,有可能队列中还没有任务就已经返回了 78 napi_run_event_loop(env, napi_event_mode_nowait); 79 } 80 return nullptr; 81 } 82 83 static napi_value RunEventLoop(napi_env env, napi_callback_info info) 84 { 85 pthread_t tid; 86 size_t argc = 1; 87 napi_value argv[1] = { nullptr }; 88 napi_get_cb_info(env, info, &argc, argv, nullptr, nullptr); 89 90 bool flag = false; 91 napi_get_value_bool(env, argv[0], &flag); 92 // 创建异步线程 93 pthread_create(&tid, nullptr, RunEventLoopFunc, &flag); 94 pthread_join(tid, nullptr); 95 96 return nullptr; 97 } 98 99 // 注册模块接口 100 EXTERN_C_START 101 static napi_value Init(napi_env env, napi_value exports) 102 { 103 napi_property_descriptor desc[] = { 104 { "runEventLoop", nullptr, RunEventLoop, nullptr, nullptr, nullptr, napi_default, nullptr } 105 }; 106 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 107 return exports; 108 } 109 EXTERN_C_END 110 111 static napi_module nativeModule = { 112 .nm_version = 1, 113 .nm_flags = 0, 114 .nm_filename = nullptr, 115 .nm_register_func = Init, 116 .nm_modname = "entry", 117 .nm_priv = nullptr, 118 .reserved = { 0 }, 119 }; 120 121 extern "C" __attribute__((constructor)) void RegisterEntryModule() 122 { 123 napi_module_register(&nativeModule); 124 } 125 ``` 126 <!-- @[napi_event_loop_cpp](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIClassicUseCases/NodeAPIApplicationScenario/entry/src/main/cpp/napi_init.cpp) --> 127 128- 接口声明 129 ```ts 130 // index.d.ts 131 export const runEventLoop: (isDefault: boolean) => object; 132 ``` 133 <!-- @[napi_event_loop_dts](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIClassicUseCases/NodeAPIApplicationScenario/entry/src/main/cpp/types/libentry/Index.d.ts) --> 134 135- 编译配置 1361. CMakeLists.txt文件需要按照如下配置 137 ``` 138 // CMakeLists.txt 139 # the minimum version of CMake. 140 cmake_minimum_required(VERSION 3.4.1) 141 project(myapplication) 142 143 set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR}) 144 145 if(DEFINED PACKAGE_FIND_FILE) 146 include(${PACKAGE_FIND_FILE}) 147 endif() 148 149 include_directories(${NATIVERENDER_ROOT_PATH} 150 ${NATIVERENDER_ROOT_PATH}/include) 151 add_library(entry SHARED napi_init.cpp) 152 target_link_libraries(entry PUBLIC libace_napi.z.so) 153 ``` 1542. 需要在模块的build-profile.json5文件中进行以下配置 155 ```json 156 { 157 "buildOption" : { 158 "arkOptions" : { 159 "runtimeOnly" : { 160 "sources": [ 161 "./src/main/ets/pages/ObjectUtils.ets" 162 ] 163 } 164 } 165 } 166 } 167 ``` 168 <!-- @[napi_event_loop_build](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIClassicUseCases/NodeAPIApplicationScenario/entry/build-profile.json5) --> 169 170- ArkTS代码示例 171 ```ts 172 // index.ets 173 import testNapi from 'libentry.so' 174 175 testNapi.runEventLoop(true); 176 ``` 177 <!-- @[napi_event_loop_ets](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIClassicUseCases/NodeAPIApplicationScenario/entry/src/main/ets/pages/Index.ets) --> 178 179 ```ts 180 // ets/pages/ObjectUtils.ets 181 export function SetTimeout() : Promise<void> { 182 return new Promise((resolve) => { 183 setTimeout(() => { 184 console.info('set timer delay 1s'); 185 // attempt to stop the event loop at napi terminal 186 resolve(); 187 }, 1000) 188 }) 189 } 190 ``` 191 <!-- @[napi_event_loop_utils](https://gitcode.com/openharmony/applications_app_samples/blob/master/code/DocsSample/ArkTS/NodeAPI/NodeAPIClassicUseCases/NodeAPIApplicationScenario/entry/src/main/ets/pages/ObjectUtils.ets) --> 192