使用Node-API接口从异步线程向ArkTS线程投递指定优先级和入队方式的任务
========================================

Node-API中的napi\_call\_threadsafe\_function\_with\_priority接口的功能是从异步线程向ArkTS线程投递指定优先级和入队方式的任务，底层队列会根据任务的优先级和入队方式来处理任务。

#### 函数说明

napi\_status napi\_call\_threadsafe\_function\_with\_priority(napi\_threadsafe\_function func, void \*data,
                                                        napi\_task\_priority priority, bool isTail);

| 参数 | 说明 |
| :-- | :-- |
| func | 线程安全方法 |
| data | 异步线程期望传递给主线程的数据 |
| priority | 指定任务的优先级[napi\_task\_priority](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/napi-data-types-interfaces#线程安全任务优先级) |
| isTail | 指定任务的入队方式，true代表任务从队列的尾部入队，false代表任务从队列的头部入队 |

#### 场景介绍

异步线程向ArkTS主线程中投递的任务需要根据任务指定的优先级和入队方式进行处理。

#### 调用异步的ArkTS接口示例

#### \[h2\]示例代码

*   功能实现
    
    #include "napi/native\_api.h"
    // ...
    #include <hilog/log.h>
    // ...
    static constexpr int INT\_ARG\_2 = 2; // 入参索引
    static constexpr int INT\_ARG\_12 = 12; // 入参索引
    static constexpr int INT\_ARG\_15 = 15; // 入参索引
    // ...
    struct CallbackData {
        napi\_threadsafe\_function tsfn;
        napi\_async\_work work;
    };
    static void CallJs(napi\_env env, napi\_value jsCb, void \*context, void \*data)
    {
        if (env == nullptr) {
            return;
        }
    
        napi\_handle\_scope scope = nullptr;
        napi\_status status = napi\_open\_handle\_scope(env, &scope);
        if (status != napi\_ok) {
            return;
        }
    
        napi\_value resultNumber = nullptr;
        napi\_value undefined = nullptr;
        napi\_get\_undefined(env, &undefined);
        napi\_value number1 = nullptr;
        napi\_create\_int32(env, INT\_ARG\_12, &number1);
        napi\_value number2 = nullptr;
        napi\_create\_int32(env, INT\_ARG\_15, &number2);
        napi\_value argv\[2\] = {number1, number2};
        napi\_call\_function(env, undefined, jsCb, INT\_ARG\_2, argv, &resultNumber);
        int32\_t res = 0;
        // 获取resultNumber对应的int32值
        napi\_get\_value\_int32(env, resultNumber, &res);
    
        napi\_close\_handle\_scope(env, scope);
    }
    
    // 异步线程中调用该接口向ArkTS线程投递指定优先级和入队方式的任务
    static void ExecuteWork(napi\_env env, void \*data)
    {
        CallbackData \*callbackData = reinterpret\_cast<CallbackData \*>(data);
        // 投递指定优先级为napi\_priority\_idle，入队方式为队列尾部入队的任务
        napi\_call\_threadsafe\_function\_with\_priority(callbackData->tsfn, nullptr, napi\_priority\_idle, true);
        // 投递指定优先级为napi\_priority\_low，入队方式为队列尾部入队的任务
        napi\_call\_threadsafe\_function\_with\_priority(callbackData->tsfn, nullptr, napi\_priority\_low, true);
        // 投递指定优先级为napi\_priority\_high，入队方式为队列尾部入队的任务
        napi\_call\_threadsafe\_function\_with\_priority(callbackData->tsfn, nullptr, napi\_priority\_high, true);
        // 投递指定优先级为napi\_priority\_immediate，入队方式为队列尾部入队的任务
        napi\_call\_threadsafe\_function\_with\_priority(callbackData->tsfn, nullptr, napi\_priority\_immediate, true);
        // 投递指定优先级为napi\_priority\_high，入队方式为队列头部入队的任务
        napi\_call\_threadsafe\_function\_with\_priority(callbackData->tsfn, nullptr, napi\_priority\_high, false);
    }
    
    static void WorkComplete(napi\_env env, napi\_status status, void \*data)
    {
        CallbackData \*callbackData = reinterpret\_cast<CallbackData \*>(data);
        if (callbackData->tsfn != nullptr) {
            napi\_release\_threadsafe\_function(callbackData->tsfn, napi\_tsfn\_release);
            callbackData->tsfn = nullptr;
        }
        if (callbackData->work != nullptr) {
            napi\_delete\_async\_work(env, callbackData->work);
            callbackData->work = nullptr;
        }
        delete callbackData;
    }
    
    static napi\_value CallThreadSafeWithPriority(napi\_env env, napi\_callback\_info info)
    {
        size\_t argc = 1;
        napi\_value jsCb = nullptr;
        CallbackData \*callbackData = new CallbackData();
        napi\_get\_cb\_info(env, info, &argc, &jsCb, nullptr, nullptr);
        napi\_value resourceName = nullptr;
        napi\_create\_string\_utf8(env, "Thread-safe Function Demo", NAPI\_AUTO\_LENGTH, &resourceName);
        if (napi\_create\_threadsafe\_function(env, jsCb, nullptr, resourceName, 0, 1, nullptr, nullptr, nullptr, CallJs,
                                            &callbackData->tsfn) != napi\_ok) {
            delete callbackData;
            return nullptr;
        }
        // 创建一个异步任务对象
        if (napi\_create\_async\_work(env, nullptr, resourceName,
                                   ExecuteWork, WorkComplete, callbackData, &callbackData->work) != napi\_ok) {
            if (callbackData->tsfn != nullptr) {
                napi\_release\_threadsafe\_function(callbackData->tsfn, napi\_tsfn\_release);
            }
            delete callbackData;
            return nullptr;
        }
        if (napi\_queue\_async\_work(env, callbackData->work) != napi\_ok) {
            if (callbackData->tsfn != nullptr) {
                napi\_release\_threadsafe\_function(callbackData->tsfn, napi\_tsfn\_release);
            }
            napi\_delete\_async\_work(env, callbackData->work);
            delete callbackData;
            return nullptr;
        }
        return nullptr;
    }
    
*   模块注册
    
    // 注册模块接口
    EXTERN\_C\_START
    static napi\_value Init(napi\_env env, napi\_value exports)
    {
        napi\_property\_descriptor desc\[\] = {
            { "callThreadSafeWithPriority", nullptr, CallThreadSafeWithPriority, nullptr, nullptr, nullptr, napi\_default, nullptr }
        };
        napi\_define\_properties(env, exports, sizeof(desc) / sizeof(desc\[0\]), desc);
        return exports;
    }
    EXTERN\_C\_END
    
    static napi\_module nativeModule = {
        .nm\_version = 1,
        .nm\_flags = 0,
        .nm\_filename = nullptr,
        .nm\_register\_func = Init,
        .nm\_modname = "entry",
        .nm\_priv = nullptr,
        .reserved = { 0 },
    };
    
    extern "C" \_\_attribute\_\_((constructor)) void RegisterEntryModule()
    {
        napi\_module\_register(&nativeModule);
    }
    
*   接口声明
    
    // index.d.ts
    export const callThreadSafeWithPriority: (cb: (a: number, b: number) => number) => void;
    
*   编译配置
    
    CMakeLists.txt文件需要按照如下配置
    
    \# the minimum version of CMake.
    cmake\_minimum\_required(VERSION 3.5.0)
    project(MyApplication3)
    
    set(NATIVERENDER\_ROOT\_PATH ${CMAKE\_CURRENT\_SOURCE\_DIR})
    
    if(DEFINED PACKAGE\_FIND\_FILE)
        include(${PACKAGE\_FIND\_FILE})
    endif()
    add\_definitions( "-DLOG\_TAG=\\"LOG\_TAG\\"" )
    include\_directories(${NATIVERENDER\_ROOT\_PATH}
                        ${NATIVERENDER\_ROOT\_PATH}/include)
    
    add\_library(entry SHARED napi\_init.cpp)
    target\_link\_libraries(entry PUBLIC libace\_napi.z.so libhilog\_ndk.z.so)
    
*   ArkTS导入头文件
    
    import testNapi from 'libentry.so';
    
*   ArkTS代码示例
    
    // index.ets
    let callback = (a: number, b: number): number => {
      console.info('result is ' + (a + b))
      return a + b;
    }
    testNapi.callThreadSafeWithPriority(callback);