#鸿蒙通关秘籍#在鸿蒙中如何使用N-API实现线程安全的跨线程函数调用?

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
疏篱菊影OLTP

在多线程环境下需要与JavaScript进行交互时,可以通过napi_create_threadsafe_function创建线程安全函数。在主线程中初始化线程安全函数,并从其他线程调用该函数进行与JavaScript的通信。步骤如下:

cpp static void CallJs(napi_env env, napi_value js_cb, void *context, void *data) { std::thread::id this_id = std::this_thread::get_id(); OH_LOG_INFO(LOG_APP, "thread CallJs %{public}d.\n", this_id); napi_status status;

status = napi_get_reference_value(env, cbObj, &js_cb);

napi_valuetype valueType = napi_undefined;
napi_typeof(env, js_cb, &valueType);
OH_LOG_INFO(LOG_APP, "CallJs js_cb is napi_function: %{public}d", valueType == napi_function);

if (env != NULL) {
    napi_value undefined, js_the_prime;
    status = napi_create_int32(env, 666, &js_the_prime);
    status = napi_get_undefined(env, &undefined);

    napi_value ret;
    status = napi_call_function(env, undefined, js_cb, 1, &js_the_prime, &ret);
}

}

napi_threadsafe_function tsfn;

static napi_value ThreadSafeTest(napi_env env, napi_callback_info info) { size_t argc = 1; napi_value js_cb, work_name; napi_status status;

status = napi_get_cb_info(env, info, &argc, &js_cb, NULL, NULL);
status = napi_create_reference(env, js_cb, 1, &cbObj);

status = napi_create_string_utf8(env, "Node-API Thread-safe Call from Async Work Item", NAPI_AUTO_LENGTH, &work_name);
std::thread::id this_id = std::this_thread::get_id();

status = napi_create_threadsafe_function(env, js_cb, NULL, work_name, 0, 1, NULL, NULL, NULL, CallJs, &tsfn);

}

std::thread t( { std::thread::id this_id = std::this_thread::get_id(); napi_status status; status = napi_acquire_threadsafe_function(tsfn); status = napi_call_threadsafe_function(tsfn, NULL, napi_tsfn_blocking); }); t.detach();

分享
微博
QQ
微信
回复
1天前
相关问题
NAPI线程调用TS线程函数
1183浏览 • 1回复 待解决