首页 > 编程语言 >HarmonyOS:Node-API典型场景开发(2)

HarmonyOS:Node-API典型场景开发(2)

时间:2024-10-26 20:32:32浏览次数:1  
标签:Node 异步 ArkTS nullptr HarmonyOS API 线程 env napi

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤博客园地址:为敢技术(https://www.cnblogs.com/strengthen/ 
➤GitHub地址:https://github.com/strengthen
➤原文地址:https://www.cnblogs.com/strengthen/p/18504462
➤如果链接不是为敢技术的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

引言

在Native侧C/C++开发场景中,对于计算简单、应用侧主线程需要实时等待结果的情况下,开发者往往会采用常见的同步方式开发业务逻辑。然而,在计算密集型场景中,对于需要执行耗时操作的逻辑,为了避免阻塞应用侧主线程,确保应用程序的性能和响应效率,开发者需要将该部分业务逻辑设计在Native侧进行异步执行。在异步开发中,开发者需要将C/C++子线程异步处理的结果反馈到ArkTS主线程,用以应用侧UI界面刷新。因此,本文将以开发案例为线索贯穿全文,来详细讲解同步开发、callback异步模型开发、promise异步模型开发以及线程安全开发等典型场景的机制原理和开发流程。

典型开发场景概述

使用Node-API进行同步任务开发

在同步任务开发中,ArkTS应用侧主线程将阻塞等待Native侧计算结果,Native侧计算结果通过方舟引擎反馈给ArkTS应用侧。此过程中,Native接口代码与ArkTS应用侧均运行在ArkTS主线程上。

比如,应用侧需要读取文件,同步模式下,应用侧程序将会一直等待Native侧文件读取完成,然后再继续运行。

使用Node-API进行异步任务开发

在异步任务开发中,应用侧在调用Native接口后,将会收到临时结果,并继续执行UI操作。Native侧将异步执行业务逻辑,不阻塞应用侧。

比如,应用侧需要读取文件,异步模式下,应用侧程序将不会等待Native侧文件读取完成,并继续运行。

 

使用Node-API进行线程安全开发

由于ArkTS天然线程安全,而Native侧代码需要开发者自行保障线程安全。Native侧C++子线程不可跨线程直接访问ArkTS对象。为此,Node-API提供了可保障线程异步执行与通信安全的机制 —— 线程安全函数。

比如,应用侧需要读取文件,使用线程安全进行实现时,应用侧程序将不会等待Native侧文件读取完成,并继续运行。

 

开发案例概述

本文将以一个图片加载的案例为背景来详细讲解上述几种典型场景的开发步骤和关键API使用方法。在此案例中,用户将通过UI界面上呈现的按钮分别选择对应的典型场景接口进行图片加载。

案例设计思路

本案例的实现分为ArkTS应用侧和Native侧两个部分,如下图所示:

ArkTS应用侧

提供多种典型场景接口按钮,以供用户进行场景选择。分别为同步调用、callback异步调用、promise异步调用、tsf(线程安全函数)异步调用以及错误图片。不同的按钮触发后,将会调用相应的Native接口进行同步或者异步处理,获取图片路径信息,从而刷新UI界面。其中,错误图片按钮反馈的是一个错误图片路径,触发后,界面上将会弹出一个错误提示弹窗。

Native侧

根据应用侧触发的不同场景,将会执行不同的接口实现。整个业务逻辑分为以下两个部分:

  • Native接口,该部分主要实现Native接口的同步处理或者异步处理逻辑。
    • 同步处理,Native接口将直接调用图片路径搜索功能,将应用侧传入的图片名称输入到生产者-消费者模型中,进行相应图片路径获取,最后反馈到ArkTS应用侧。
    • 异步处理,Native接口将通过异步工作项或者线程安全函数进行异步任务创建,将应用侧传入的图片名称输入到上下文数据对象中,待后续异步任务调度处理。在异步任务处理中,同样调度生产者-消费者模型进行图片路径获取,最后通过线程通信将结果反馈到ArkTS应用侧。
  • 生产者-消费者模型,该部分逻辑主要通过C++子线程、信号量以及条件变量等关键特性来实现。
    • 生产者线程负责根据图片名称搜索目标图片路径。并且将搜索结果放入缓冲队列中。
    • 消费者线程负责从缓冲队列中取出目标图片路径,并通过线程通信的方式将结果反馈到ArkTS应用侧。

案例流程图

案例效果图

生产者-消费者模型实现

(1)模型缓冲队列

ProducerConsumer.h 头文件

#ifndef MultiThreads_ProducerConsumer_H
#define MultiThreads_ProducerConsumer_H

#include <string>
#include <queue>
#include <mutex>
#include <condition_variable>

using namespace std;
// Principles of the producer-consumer model: Use buffer zones to balance the rate between production and consumption.
// Synchronization relationship 1: When the buffer is full, the producer needs to be blocked and wait. When a product
// pops up the buffer, the producer needs to be woken up for consumption. Synchronization relationship 2: When the
// buffer is empty, the consumer needs to be blocked and waited. When a product enters the buffer, the consumer needs to
// be woken up for consumption.
class ProducerConsumerQueue {
public:
    // constructor
    ProducerConsumerQueue() {}
    ProducerConsumerQueue(int queueSize) : m_maxSize(queueSize) {}
    // producer enqueue operation
    void PutElement(string element);
    // consumer dequeue operation
    string TakeElement();
private:
    // check whether the buffer queue is full
    bool isFull() { return (m_queue.size() == m_maxSize); }
    // check whether the buffer queue is empty
    bool isEmpty() { return m_queue.empty(); }
private:
    queue<string> m_queue{};         // buffer queue
    int m_maxSize{};                 // buffer queue capacity
    mutex m_mutex{};                 // the mutex is used to protect data consistency
    condition_variable m_notEmpty{}; // condition variable, which is used to indicate whether the buffer queue is empty
    condition_variable m_notFull{};  // condition variable, which is used to indicate whether the buffer queue is full
};
#endif // MultiThreads_ProducerConsumer_H

ProducerConsumer.cpp 源文件

   
  1. #include "ProducerConsumer.h"
  2. void ProducerConsumerQueue::PutElement(string element) {
  3. unique_lock<mutex> lock(m_mutex); // add mutex
  4. while (isFull()) {
  5. // when the data buffer queue is full, the production is blocked and wakes up after consumer consumption
  6. // m_mutex is automatically released at the same time
  7. m_notFull.wait(lock);
  8. }
  9. // reacquire the lock
  10. // if the queue is not full
  11. // the product is added to the queue and the consumer is notified that the product can be consumed
  12. m_queue.push(element);
  13. m_notEmpty.notify_one();
  14. }
  15. string ProducerConsumerQueue::TakeElement() {
  16. unique_lock<mutex> lock(m_mutex); // add mutex
  17. while (isEmpty()) {
  18. // when the data buffer queue is empty, the consumption is blocked and the producer is woken up after production
  19. // m_mutex is automatically released at the same time
  20. m_notEmpty.wait(lock);
  21. }
  22. // reacquire the lock
  23. // if the queue is not empty, the product is ejected and the producer is notified that it is ready for production
  24. string element = m_queue.front();
  25. m_queue.pop();
  26. m_notFull.notify_one();
  27. return element;
  28. }

(2)全局变量及搜索接口定义

定义一个静态全局的模型缓冲队列。由于,每次只处理一张图片,所以将容量设定为1。

定义一个静态全局的图片路径集合,用于后文搜索。

MultiThreads.cpp文件

   
  1. // define the buffer queue and set the capacity to 1
  2. static ProducerConsumerQueue buffQueue(1);
  3. // defines the image path set, which is used for later search
  4. static vector<string> imagePathVec{"sync.png", "callback.png", "promise.png", "tsf.png"};
  5. // check the image paths based on the image name
  6. static bool CheckImagePath(const string &imageName, const string &imagePath) {
  7. // separate character strings by suffix
  8. size_t pos = imagePath.find_first_of('.');
  9. if (pos == string::npos) {
  10. return false;
  11. }
  12. string nameTemp = imagePath.substr(0, pos);
  13. if (nameTemp.empty()) {
  14. return false;
  15. }
  16. // determine whether the image path is the target path based on whether the image names are the same
  17. return (imageName == nameTemp);
  18. }
  19. // search for image paths by image name
  20. static string SearchImagePath(const string &imageName) {
  21. for (const string &imagePath : imagePathVec) {
  22. if (CheckImagePath(imageName, imagePath)) {
  23. return imagePath;
  24. }
  25. }
  26. return string("");
  27. }

(3)生产者线程执行函数

生产者线程的执行功能:通过解析上下文数据中的图片名称参数,来搜索相应的图片路径,并将其置入模型缓冲队列中。

MultiThreads.cpp文件

   
  1. static void ProductElement(void *data) {
  2. buffQueue.PutElement(SearchImagePath(static_cast<ContextData *>(data)->args));
  3. }

(4)消费者线程执行函数

消费者线程的执行功能:通过从模型缓冲队列中获取图片路径的搜索结果,并将其置入上下文数据中,用以后续反馈给ArkTS应用侧。

MultiThreads.cpp文件

非线程安全函数消费者执行函数:

   
  1. static void ConsumeElement(void *data) { static_cast<ContextData *>(data)->result = buffQueue.TakeElement(); }

线程安全函数消费者执行函数:

   
  1. static void ConsumeElementTSF(void *data) {
  2. static_cast<ContextData *>(data)->result = buffQueue.TakeElement();
  3. // bind consumer thread to the thread safe function
  4. (void)napi_acquire_threadsafe_function(tsFun);
  5. // send async task to the JS main thread EventLoop
  6. (void)napi_call_threadsafe_function(tsFun, data, napi_tsfn_blocking);
  7. // release thread reference
  8. (void)napi_release_threadsafe_function(tsFun, napi_tsfn_release);
  9. }

使用Node-API进行同步任务开发

在同步任务开发中,ArkTS应用侧主线程将阻塞等待Native侧计算结果,Native侧计算结果通过方舟引擎反馈给ArkTS应用侧。此过程中,Native接口代码与ArkTS应用侧均运行在ArkTS主线程上。为了Native侧业务处理具有同步效果,案例中的生产者与消费者线程则采用join()的方式来进行同步处理。

同步调用也支持带Callback,具体方式由应用开发者决定,通过是否传递Callback函数进行区分。

同步任务开发时序交互图

 

从上图中,可以看出,当Native同步任务接口被调用时,该接口会完成参数解析、数据类型转换、创建生产者和消费者线程等。在等待生产者线程和消费者线程执行结束后,将图片路径结果转换为napi_value,由方舟引擎直接反馈到ArkTS应用侧。

同步任务开发步骤

(1)ArkTS应用侧开发

用户在界面点击“多线程同步调用”按钮,触发onClick()回调。在回调处理中,将会调用Native接口进行图片路径获取,以刷新UI界面。

Index.ets文件    
  1. import testNapi from 'libentry.so';
  2. import Constants from '../../common/constants/CommonConstants';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State imagePath: string = Constants.INIT_IMAGE_PATH;
  7. imageName: string = '';
  8. build() {
  9. Column() {
  10. ...
  11. // button list, prompting the user to click the button to select the target image.
  12. Column() {
  13. ...
  14. // multi-threads sync call button
  15. Button($r('app.string.sync_button_title'))
  16. .width(Constants.FULL_PARENT)
  17. .margin($r('app.float.button_common_margin'))
  18. .onClick(() => {
  19. this.imageName = Constants.SYNC_BUTTON_IMAGE;
  20. this.imagePath = Constants.IMAGE_ROOT_PATH + testNapi.getImagePathSync(this.imageName);
  21. })
  22. ...
  23. }
  24. ...
  25. }
  26. ...
  27. }
  28. }

(2)Native侧开发

在同步任务开发中,Native侧接口原生代码仍然运行在ArkTS主线程上。

导出Native接口:将Native接口导出到ArkTS侧,用于支撑ArkTS对象调用和模块编译构建。

index.d.ts文件

   
  1. // export sync interface
  2. export const getImagePathSync: (imageName: string) => string;

上下文数据结构定义:用于任务执行过程中,上下文数据存储。后文异步任务开发和线程安全开发中实现相同,后续不再赘述。

MultiThreads.cpp文件

   
  1. // context data provided by users
  2. // data is transferred between the native method (initialization data), ExecuteFunc, and CompleteFunc
  3. struct ContextData {
  4. napi_async_work asyncWork = nullptr; // async work object
  5. napi_deferred deferred = nullptr; // associated object of the delay object promise
  6. napi_ref callbackRef = nullptr; // reference of callback
  7. string args = ""; // parameters from ArkTS --- imageName
  8. string result = ""; // C++ sub-thread calculation result --- imagePath
  9. };

销毁上下文数据:在任务执行结束或者失败后,需要销毁上下文数据进行内存释放。后文异步任务开发和线程安全开发中实现相同,后续不再赘述。

MultiThreads.cpp文件

   
  1. static void DeleteContext(napi_env env, ContextData *contextData) {
  2. // delete callback reference
  3. if (contextData->callbackRef != nullptr) {
  4. (void)napi_delete_reference(env, contextData->callbackRef);
  5. }
  6. // delete async work
  7. if (contextData->asyncWork != nullptr) {
  8. (void)napi_delete_async_work(env, contextData->asyncWork);
  9. }
  10. // release context data
  11. delete contextData;
  12. }

Native同步任务开发接口:解析ArkTS应用侧参数、数据类型转换、创建生产者和消费者线程,并使用join()进行同步处理。最后在获取结果后,将数据转换为napi_value类型,返回给ArkTS应用侧。

MultiThreads.cpp文件

   
  1. // sync interface
  2. static napi_value GetImagePathSync(napi_env env, napi_callback_info info) {
  3. size_t paraNum = 1;
  4. napi_value paraArray[1] = {nullptr};
  5. // parse parameters
  6. napi_status operStatus = napi_get_cb_info(env, info, &paraNum, paraArray, nullptr, nullptr);
  7. if (operStatus != napi_ok) {
  8. return nullptr;
  9. }
  10. napi_valuetype paraDataType = napi_undefined;
  11. operStatus = napi_typeof(env, paraArray[0], &paraDataType);
  12. if ((operStatus != napi_ok) || (paraDataType != napi_string)) {
  13. return nullptr;
  14. }
  15. // convert napi_value to char *
  16. constexpr size_t buffSize = 100;
  17. char strBuff[buffSize]{}; // char buffer for imageName string
  18. size_t strLength = 0;
  19. operStatus = napi_get_value_string_utf8(env, paraArray[0], strBuff, buffSize, &strLength);
  20. if ((operStatus != napi_ok) || (strLength == 0)) {
  21. return nullptr;
  22. }
  23. // defines context data. the memory will be released in CompleteFunc
  24. auto contextData = new ContextData;
  25. contextData->args = strBuff;
  26. // create producer thread
  27. thread producer(ProductElement, static_cast<void *>(contextData));
  28. producer.join();
  29. // create consumer thread
  30. thread consumer(ConsumeElement, static_cast<void *>(contextData));
  31. consumer.join();
  32. // convert the result to napi_value and send it to ArkTs application
  33. napi_value result = nullptr;
  34. (void)napi_create_string_utf8(env, contextData->result.c_str(), contextData->result.length(), &result);
  35. // delete context data
  36. DeleteContext(env, contextData);
  37. return result;
  38. }

使用Node-API进行异步任务开发

Node-API异步任务机制概述

Node-API异步任务开发主要用于执行耗时操作的场景中使用,以避免阻塞主线程,确保应用程序的性能和响应效率。例如以下场景:

  • 文件操作:读取大型文件或执行复杂的文件操作时,可以使用异步工作项来避免阻塞主线程。
  • 网络请求:当需要进行网络请求并等待响应时,可以使用异步工作项来避免阻塞主线程,从而提高应用程序的响应性能。
  • 数据库操作:当需要执行复杂的数据库查询或写入操作时,可以使用异步工作项来避免阻塞主线程,从而提高应用程序的并发性能。
  • 图形处理:当需要对大型图像进行处理或执行复杂的图像算法时,可以使用异步工作项来避免阻塞主线程,从而提高应用程序的实时性能。

异步方式与同步方式的区别在于,同步方式中所有代码的处理都在ArkTS主线程中完成,而异步方式中的所有代码在多线程中完成。Node-API主要是通过创建一个异步工作项来实现异步任务开发。总体步骤如下:

  1. 在Native接口函数中,创建一个异步工作项,并置入libuv调度队列中,然后立即返回一个临时结果给ArkTS调用者;
  2. 通过libuv线程池创建并调度work子线程完成异步业务逻辑的执行;
  3. 通过Callback回调或者Promise延时对象返回真正的处理结果,并用于应用侧UI刷新。

异步工作项的底层机制是基于libuv异步库来实现的,具体流程原理如下:

异步方式依赖Node-API提供的napi_create_async_work接口创建异步工作项:

   
  1. NAPI_EXTERN napi_status napi_create_async_work(napi_env env,
  2. napi_value async_resource,
  3. napi_value async_resource_name,
  4. napi_async_execute_callback execute,
  5. napi_async_complete_callback complete,
  6. void* data,
  7. napi_async_work* result);
  8. 参数说明:
  9. [in] env:传入接口调用者的环境,包含方舟引擎等。由框架提供,默认情况下直接传入即可。
  10. [in] async_resource:可选项,关联async_hooks。
  11. [in] async_resource_name:异步资源标识符,主要用于async_hooks API暴露断言诊断信息。
  12. [in] execute:执行业务逻辑计算函数,由libuv线程池调度执行。在该函数中执行IO、CPU密集型任务,不阻塞主线程。
  13. [in] complete:execute回调函数执行完成或取消后,触发执行该函数。此函数在EventLoop子线程中执行。
  14. [in] data:用户提供的上下文数据,用于传递数据。
  15. [out] result:napi_async_work*指针,用于返回当前此处函数调用创建的异步工作项。 返回值:返回napi_ok表示转换成功,其他值失败。

Execute回调

  • execute函数用于执行工作项的业务逻辑,异步工作项被调度后,该函数从上下文数据中获取输入数据,在work子线程中完成业务逻辑计算(不阻塞主线程)并将结果写入上下文数据。
  • 因为execute函数不在ArkTS线程中,所以不允许execute函数调用napi的接口。业务逻辑的返回值可以返回到complete回调中处理。

Complete回调

  • 业务逻辑处理execute函数执行完成或被取消后,通过事件通知EventLoop执行complete函数,complete函数从上下文数据中获取结果,转换为napi_value类型,调用ArkTS回调函数或通过Promise resolve()返回结果。
  • 该函数运行在ArkTS主线程下,因此可以调用napi的接口,将execute中的返回值封装成ArkTS对象返回。

Node-API异步接口实现支持Callback方式和Promise方式,具体使用哪种方式由应用开发者决定,通过是否传递callback函数进行区分。下文将对两种异步模型作简要介绍:

Callback异步模型

  • 用户在调用Native接口的时候,Native接口将异步执行任务,并临时返回空值给ArkTS应用侧。
  • 异步任务执行结果以参数的形式提供给用户注册的ArkTS回调函数,并通过napi_call_function将ArkTS回调函数进行调用执行以反馈结果到ArkTS应用侧。

Promise异步模型

  • 用户在调用Native接口的时候,Native接口将异步执行任务,并返回一个Promise对象给ArkTS应用侧。
  • Promise对象提供了API使得异步执行可以按照同步的流程表示出来,避免了层层嵌套的回调引用。
  • 异步任务执行结果以参数的形式提供给与ArkTS应用侧Promise对象关联的deferred对象,并通过napi_resolve_deferred将计算结果反馈到ArkTS应用侧。

异步任务开发时序交互图

(一)Callback异步开发时序交互

(2)Promise异步开发时序交互

从上图中,可以看出,当Native异步任务接口被调用时,该接口会完成参数解析、数据类型转换、异步工作项创建、异步任务压入调度队列以及返回空值(Callback方式)或者Promise对象(Promise方式)等。异步任务的调度、执行以及反馈计算结果,均由libuv线程池和EventLoop机制进行系统调度完成。

异步任务开发步骤

(一)Callback异步开发步骤

(1)ArkTS应用侧开发

用户在界面点击“多线程callback异步调用”按钮,触发onClick()回调。在回调处理中,将会调用Native接口进行图片路径获取,以刷新UI界面。

Index.ets文件

   
  1. import testNapi from 'libentry.so';
  2. import Constants from '../../common/constants/CommonConstants';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State imagePath: string = Constants.INIT_IMAGE_PATH;
  7. imageName: string = '';
  8. build() {
  9. Column() {
  10. ...
  11. // button list, prompting the user to click the button to select the target image.
  12. Column() {
  13. ...
  14. // multi-threads callback async button
  15. Button($r('app.string.async_callback_button_title'))
  16. .width(Constants.FULL_PARENT)
  17. .margin($r('app.float.button_common_margin'))
  18. .onClick(() => {
  19. this.imageName = Constants.CALLBACK_BUTTON_IMAGE;
  20. testNapi.getImagePathAsyncCallBack(this.imageName, (result: string) => {
  21. this.imagePath = Constants.IMAGE_ROOT_PATH + result;
  22. });
  23. })
  24. ...
  25. }
  26. ...
  27. }
  28. ...
  29. }
  30. }

(2)Native侧开发

导出Native接口:将Native接口导出到ArkTS侧,用于支撑ArkTS对象调用和模块编译构建。

index.d.ts文件

   
  1. // export async callback interface
  2. export const getImagePathAsyncCallBack: (imageName: string, callBack: (result: string) => void) => void;

execute回调:定义异步工作项的第一个回调函数,该函数在work子线程中执行,处理具体的业务逻辑。

MultiThreads.cpp文件

   
  1. static void ExecuteFunc([[maybe_unused]] napi_env env, void *data) {
  2. // create producer thread
  3. thread producer(ProductElement, data);
  4. // the producer and consumer threads must be synchronized
  5. // otherwise, the complete operation is triggered to communicate with the ArkTS after the executeFunc is complete
  6. // the result is unpredictable
  7. producer.join();
  8. // create consumer thread
  9. thread consumer(ConsumeElement, data);
  10. consumer.join();
  11. }

complete回调:定义异步工作项的第二个回调函数,该函数在ArkTS主线程中执行,将结果传递给ArkTS侧。

MultiThreads.cpp文件

   
  1. static void CompleteFuncCallBack(napi_env env, [[maybe_unused]] napi_status status, void *data) {
  2. // parse context data
  3. ContextData *contextData = static_cast<ContextData *>(data);
  4. napi_value callBack = nullptr;
  5. napi_status operStatus = napi_get_reference_value(env, contextData->callbackRef, &callBack);
  6. if (operStatus != napi_ok) {
  7. DeleteContext(env, contextData);
  8. return;
  9. }
  10. // define the undefined variable, which is used in napi_call_function
  11. // because no other data is transferred, the variable is defined as undefined
  12. napi_value undefined = nullptr;
  13. operStatus = napi_get_undefined(env, &undefined);
  14. if (operStatus != napi_ok) {
  15. DeleteContext(env, contextData);
  16. return;
  17. }
  18. // convert the calculation result of C++ sub-thread to the napi_value type
  19. napi_value callBackArgs = nullptr;
  20. operStatus = napi_create_string_utf8(env, contextData->result.c_str(),
  21. contextData->result.length(), &callBackArgs);
  22. if (operStatus != napi_ok) {
  23. DeleteContext(env, contextData);
  24. return;
  25. }
  26. // call the JS callback and send the async calculation result on the Native to ArkTS application
  27. napi_value callBackResult = nullptr;
  28. (void)napi_call_function(env, undefined, callBack, 1, &callBackArgs, &callBackResult);
  29. // destroy data and release memory
  30. DeleteContext(env, contextData);
  31. }

Native异步任务开发接口:解析ArkTS应用侧参数,使用napi_create_async_work创建异步工作项,并使用napi_queue_async_work将异步任务加入队列,等待调度执行。

MultiThreads.cpp文件

   
  1. // callback async interface
  2. static napi_value GetImagePathAsyncCallBack(napi_env env, napi_callback_info info) {
  3. size_t paraNum = 2;
  4. napi_value paraArray[2] = {nullptr};
  5. // parse parameters
  6. napi_status operStatus = napi_get_cb_info(env, info, &paraNum, paraArray, nullptr, nullptr);
  7. if (operStatus != napi_ok) {
  8. return nullptr;
  9. }
  10. napi_valuetype paraDataType = napi_undefined;
  11. operStatus = napi_typeof(env, paraArray[0], &paraDataType);
  12. if ((operStatus != napi_ok) || (paraDataType != napi_string)) {
  13. return nullptr;
  14. }
  15. operStatus = napi_typeof(env, paraArray[1], &paraDataType);
  16. if ((operStatus != napi_ok) || (paraDataType != napi_function)) {
  17. return nullptr;
  18. }
  19. // napi_value convert to char *
  20. constexpr size_t buffSize = 100;
  21. char strBuff[buffSize]{}; // char buffer for imageName string
  22. size_t strLength = 0;
  23. operStatus = napi_get_value_string_utf8(env, paraArray[0], strBuff, buffSize, &strLength);
  24. if ((operStatus != napi_ok) || (strLength == 0)) {
  25. return nullptr;
  26. }
  27. // defines context data. the memory will be released in CompleteFunc
  28. auto contextData = new ContextData;
  29. contextData->args = strBuff;
  30. operStatus = napi_create_reference(env, paraArray[1], 1, &contextData->callbackRef);
  31. if (operStatus != napi_ok) {
  32. DeleteContext(env, contextData);
  33. return nullptr;
  34. }
  35. // async resource
  36. napi_value asyncName = nullptr;
  37. string asyncStr = "async callback";
  38. operStatus = napi_create_string_utf8(env, asyncStr.c_str(), asyncStr.length(), &asyncName);
  39. if (operStatus != napi_ok) {
  40. DeleteContext(env, contextData);
  41. return nullptr;
  42. }
  43. // create async work
  44. operStatus = napi_create_async_work(env, nullptr, asyncName, ExecuteFunc, CompleteFuncCallBack,
  45. static_cast<void *>(contextData), &contextData->asyncWork);
  46. if (operStatus != napi_ok) {
  47. DeleteContext(env, contextData);
  48. return nullptr;
  49. }
  50. // add the async work to the queue and wait for scheduling
  51. operStatus = napi_queue_async_work(env, contextData->asyncWork);
  52. if (operStatus != napi_ok) {
  53. DeleteContext(env, contextData);
  54. }
  55. return nullptr;
  56. }

(二)Promise异步开发步骤

(1)ArkTS应用侧开发

用户在界面点击“多线程promise异步调用”按钮,触发onClick()回调。在回调处理中,将会调用Native接口进行图片路径获取,以刷新UI界面。

Index.ets文件

   
  1. import testNapi from 'libentry.so';
  2. import Constants from '../../common/constants/CommonConstants';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State imagePath: string = Constants.INIT_IMAGE_PATH;
  7. imageName: string = '';
  8. build() {
  9. Column() {
  10. ...
  11. // button list, prompting the user to click the button to select the target image.
  12. Column() {
  13. ...
  14. // multi-threads promise async button
  15. Button($r('app.string.async_promise_button_title'))
  16. .width(Constants.FULL_PARENT)
  17. .margin($r('app.float.button_common_margin'))
  18. .onClick(() => {
  19. this.imageName = Constants.PROMISE_BUTTON_IMAGE;
  20. let promiseObj = testNapi.getImagePathAsyncPromise(this.imageName);
  21. promiseObj.then((result: string) => {
  22. this.imagePath = Constants.IMAGE_ROOT_PATH + result;
  23. })
  24. })
  25. ...
  26. }
  27. ...
  28. }
  29. ...
  30. }
  31. }

(2)Native侧开发

导出Native接口:将Native接口导出到ArkTS侧,用于支撑ArkTS对象调用和模块编译构建。

index.d.ts文件

   
  1. // export async promise interface
  2. export const getImagePathAsyncPromise: (imageName: string) => Promise<string>;

execute回调:定义异步工作项的第一个回调函数,该函数在work子线程中执行,处理具体的业务逻辑。

MultiThreads.cpp文件

   
  1. static void ExecuteFunc([[maybe_unused]] napi_env env, void *data) {
  2. // create producer thread
  3. thread producer(ProductElement, data);
  4. // the producer and consumer threads must be synchronized
  5. // otherwise, the complete operation is triggered to communicate with the ArkTS after the executeFunc is complete
  6. // the result is unpredictable
  7. producer.join();
  8. // create consumer thread
  9. thread consumer(ConsumeElement, data);
  10. consumer.join();
  11. }

complete回调:定义异步工作项的第二个回调函数,该函数在ArkTS主线程中执行,将结果传递给ArkTS侧。

MultiThreads.cpp文件

   
  1. static void CompleteFuncPromise(napi_env env, [[maybe_unused]] napi_status status, void *data) {
  2. // parse context data
  3. ContextData *contextData = static_cast<ContextData *>(data);
  4. // convert the calculation result of C++ sub-thread to the napi_value type
  5. napi_value promiseArgs = nullptr;
  6. napi_status operStatus =
  7. napi_create_string_utf8(env, contextData->result.c_str(), contextData->result.length(), &promiseArgs);
  8. if (operStatus != napi_ok) {
  9. DeleteContext(env, contextData);
  10. return;
  11. }
  12. // the deferred and promise object are associated. the result is sent to ArkTS application through this interface
  13. operStatus = napi_resolve_deferred(env, contextData->deferred, promiseArgs);
  14. if (operStatus != napi_ok) {
  15. DeleteContext(env, contextData);
  16. return;
  17. }
  18. // destroy data and release memory
  19. DeleteContext(env, contextData);
  20. }

Native异步任务开发接口:解析ArkTS应用侧参数,使用napi_create_async_work创建异步工作项,并使用napi_queue_async_work将异步任务加入队列,等待调度执行。

MultiThreads.cpp文件

   
  1. // promise async interface
  2. static napi_value GetImagePathAsyncPromise(napi_env env, napi_callback_info info) {
  3. size_t paraNum = 1;
  4. napi_value paraArray[1] = {nullptr};
  5. // parse parameters
  6. napi_status operStatus = napi_get_cb_info(env, info, &paraNum, paraArray, nullptr, nullptr);
  7. if (operStatus != napi_ok) {
  8. return nullptr;
  9. }
  10. napi_valuetype paraDataType = napi_undefined;
  11. operStatus = napi_typeof(env, paraArray[0], &paraDataType);
  12. if ((operStatus != napi_ok) || (paraDataType != napi_string)) {
  13. return nullptr;
  14. }
  15. // napi_value convert to char *
  16. constexpr size_t buffSize = 100;
  17. char strBuff[buffSize]{}; // char buffer for imageName string
  18. size_t strLength = 0;
  19. operStatus = napi_get_value_string_utf8(env, paraArray[0], strBuff, buffSize, &strLength);
  20. if ((operStatus != napi_ok) || (strLength == 0)) {
  21. return nullptr;
  22. }
  23. // defines context data. the memory will be released in CompleteFunc
  24. auto contextData = new ContextData;
  25. contextData->args = strBuff;
  26. // async resource
  27. napi_value asyncName = nullptr;
  28. string asyncStr = "async promise";
  29. operStatus = napi_create_string_utf8(env, asyncStr.c_str(), asyncStr.length(), &asyncName);
  30. if (operStatus != napi_ok) {
  31. DeleteContext(env, contextData);
  32. return nullptr;
  33. }
  34. // create async work
  35. operStatus = napi_create_async_work(env, nullptr, asyncName, ExecuteFunc, CompleteFuncPromise,
  36. static_cast<void *>(contextData), &contextData->asyncWork);
  37. if (operStatus != napi_ok) {
  38. DeleteContext(env, contextData);
  39. return nullptr;
  40. }
  41. // add the async work to the queue and wait for scheduling
  42. operStatus = napi_queue_async_work(env, contextData->asyncWork);
  43. if (operStatus != napi_ok) {
  44. DeleteContext(env, contextData);
  45. return nullptr;
  46. }
  47. // create promise object
  48. napi_value promiseObj = nullptr;
  49. operStatus = napi_create_promise(env, &contextData->deferred, &promiseObj);
  50. if (operStatus != napi_ok) {
  51. DeleteContext(env, contextData);
  52. return nullptr;
  53. }
  54. return promiseObj;
  55. }

使用Node-API进行线程安全开发

Node-API线程安全机制概述

Node-API线程安全开发主要用于异步多线程之间共享和调用场景中使用,以避免出现竞争条件或死锁。例如以下场景:

  • 异步计算:如果需要进行耗时的计算或IO操作,可以创建一个线程安全函数,将计算或IO操作放在另一个线程中执行,避免阻塞主线程,提高程序的响应速度。
  • 数据共享:如果多个线程需要访问同一份数据,可以创建一个线程安全函数,确保数据的读写操作不会发生竞争条件或死锁等问题。
  • 多线程开发:如果需要进行多线程开发,可以创建一个线程安全函数,确保多个线程之间的通信和同步操作正确无误。

Node-API接口只能在ArkTS主线程上进行调用。当C++子线程或者work子线程需要调用ArkTS回调接口或者Node-API接口时,这些线程是需要与ArkTS主线程进行通信才能完成的。Node-API提供了类型napi_threadsafe_function(线程安全函数)以及创建、销毁和调用该类型对象的 API来完成此操作。Node-API主要是通过创建一个线程安全函数,然后在C++子线程或者work子线程中调用线程安全函数来实现线程安全开发。总体步骤如下:

  1. 在Native接口函数中,创建一个线程安全函数对象,并注册绑定ArkTS回调接口callback和线程安全回调函数call_js_cb,然后立即返回一个临时结果给ArkTS调用者;
  2. 通过系统调度C++子线程完成异步业务逻辑的执行,并在子线程的执行函数中调用napi_call_threadsafe_function,将call_js_cb抛给EventLoop事件循环进行调度;
  3. 通过call_js_cb执行,调用napi_call_function调用ArkTS回调接口callback,从而将异步计算结果反馈到ArkTS应用侧,用于应用侧UI刷新。

线程安全函数的底层机制依然是基于libuv异步库来实现的,其原理流程如下:

 

线程安全函数机制中关键的两个接口napi_create_threadsafe_function()和napi_call_threadsafe_function()参数列表详解:

napi_create_threadsafe_function

该接口主要用于创建线程安全对象,在创建的过程中,会注册异步过程中的关键信息:ArkTS侧回调接口callback、线程安全回调函数call_js_cb等。

   
  1. NAPI_EXTERN napi_status napi_create_threadsafe_function(napi_env env,
  2. napi_value func,
  3. napi_value async_resource,
  4. napi_value async_resource_name,
  5. size_t max_queue_size,
  6. size_t initial_thread_count,
  7. void* thread_finalize_data,
  8. napi_finalize thread_finalize_cb,
  9. void* context,
  10. napi_threadsafe_function_call_js call_js_cb,
  11. napi_threadsafe_function* result);
  12. 参数说明:
  13. [in] env:传入接口调用者的环境,包含方舟引擎等。由框架提供,默认情况下直接传入即可。
  14. [in] func:ArkTS应用侧传入的回调接口callback,可为空。当该值为nullptr时,下文call_js_cb不能为nullptr。反之,亦然。两者不可同时为空。
  15. [in] async_resource:关联async_hooks,可为空。
  16. [in] async_resource_name:异步资源标识符,主要用于async_hooks API暴露断言诊断信息。
  17. [in] max_queue_size:缓冲队列容量,0表示无限制。线程安全函数实现实质为生产者-消费者模型。
  18. [in] initial_thread_count:初始线程,包括将使用此函数的主线程,可为空。
  19. [in] thread_finalize_data:传递给thread_finalize_cb接口的参数,可为空。
  20. [in] thread_finalize_cb:当线程安全函数结束释放时的回调接口,可为空。
  21. [in] context:附加的上下文数据,可为空。
  22. [in] call_js_cb:子线程需要处理的线程安全回调任务,类似于异步工作项中的complete回调。当调用napi_call_threadsafe_function后,被抛到ArkTS主线程EventLoop中,等待调度执行。当该值为空时,系统将会调用默认回调接口。
  23. [out] result:线程安全函数对象指针。

napi_call_threadsafe_function

该接口主要用于子线程中,将需要回到ArkTS主线程处理的任务抛到EventLoop中,等待调度执行。

   
  1. NAPI_EXTERN napi_status napi_call_threadsafe_function(napi_threadsafe_function func, void* data, napi_threadsafe_function_call_mode is_blocking);
  2. 参数说明:
  3. [in] func:线程安全函数对象。
  4. [in] data:上述线程安全回调任务call_js_cb需要处理的数据。
  5. [in] is_blocking:该参数控制接口是否以阻塞的方式运行。
  6. 如果参数为napi_tsfn_nonblocking,该接口将以非阻塞的方式运行。当缓冲队列已满,调用该接口后,则返回napi_queue_full错误码。
  7. 如果参数为napi_tsfn_blocking,该接口将以阻塞的方式运行,直到缓冲队列中有可用空间。
  8. 如果创建线程安全函数时,设置的最大队列容量为0,则napi_call_threadsafe_function()永远不会阻塞。

线程安全开发时序交互图

 

从上图中,可以看出,当Native线程安全异步接口被调用时,该接口会完成参数解析、数据类型转换、线程安全创建、在创建过程中的注册绑定ArkTS回调处理函数以及创建生产者和消费者线程等。异步任务的调度、执行以及反馈计算结果,均由C++子线程和EventLoop机制进行系统调度完成。

线程安全开发步骤

(1)ArkTS应用侧开发

用户在界面点击“多线程tsf异步调用”按钮,触发onClick()回调。在回调处理中,将会调用Native接口进行图片路径获取,以刷新UI界面。

Index.ets文件    
  1. import testNapi from 'libentry.so';
  2. import Constants from '../../common/constants/CommonConstants';
  3. @Entry
  4. @Component
  5. struct Index {
  6. @State imagePath: string = Constants.INIT_IMAGE_PATH;
  7. imageName: string = '';
  8. build() {
  9. Column() {
  10. ...
  11. // button list, prompting the user to click the button to select the target image.
  12. Column() {
  13. ...
  14. // multi-threads tsf async button
  15. Button($r('app.string.async_tsf_button_title'))
  16. .width(Constants.FULL_PARENT)
  17. .margin($r('app.float.button_common_margin'))
  18. .onClick(() => {
  19. this.imageName = Constants.TSF_BUTTON_IMAGE;
  20. testNapi.getImagePathAsyncTSF(this.imageName, (result: string) => {
  21. this.imagePath = Constants.IMAGE_ROOT_PATH + result;
  22. });
  23. })
  24. ...
  25. }
  26. ...
  27. }
  28. ...
  29. }
  30. }

(2)Native侧开发

导出Native接口:将Native接口导出到ArkTS侧,用于支撑ArkTS对象调用和模块编译构建。

index.d.ts文件

   
  1. // export thread safe function interface
  2. export const getImagePathAsyncTSF: (imageName: string, callBack: (result: string) => void) => void;

全局变量定义:定义线程安全函数对象、队列容量、初始化线程数。

MultiThreads.cpp文件

   
  1. // define global thread safe function
  2. static napi_threadsafe_function tsFun = nullptr;
  3. static constexpr int MAX_MSG_QUEUE_SIZE = 0; // indicates that the queue length is not limited
  4. static constexpr int INITIAL_THREAD_COUNT = 1;

call_js_cb回调处理定义:定义消费者子线程中,通过napi_call_threadsafe_function抛到ArkTS主线程EventLoop中的回调处理函数。在该函数中,通过napi_call_function调用ArkTS应用侧传入的回调callback,将异步任务搜索到的图片路径结果反馈到ArkTS应用侧。

MultiThreads.cpp文件

   
  1. static void CallJsFunction(napi_env env, napi_value callBack, [[maybe_unused]] void *context, void *data) {
  2. // parse context data
  3. ContextData *contextData = static_cast<ContextData *>(data);
  4. // define the undefined variable, which is used in napi_call_function
  5. // because no other data is transferred, the variable is defined as undefined
  6. napi_value undefined = nullptr;
  7. napi_status operStatus = napi_get_undefined(env, &undefined);
  8. if (operStatus != napi_ok) {
  9. DeleteContext(env, contextData);
  10. return;
  11. }
  12. // convert the calculation result of C++ sub-thread to the napi_value type
  13. napi_value callBackArgs = nullptr;
  14. operStatus = napi_create_string_utf8(env, contextData->result.c_str(), contextData->result.length(), &callBackArgs);
  15. if (operStatus != napi_ok) {
  16. DeleteContext(env, contextData);
  17. return;
  18. }
  19. // call the JS callback and send the async calculation result on the Native to ArkTS application
  20. napi_value callBackResult = nullptr;
  21. (void)napi_call_function(env, undefined, callBack, 1, &callBackArgs, &callBackResult);
  22. // destroy data and release memory
  23. DeleteContext(env, contextData);
  24. }

Native线程安全函数异步开发接口:解析ArkTS应用侧参数,使用napi_create_threadsafe_function创建线程安全函数对象,并在消费者线程执行函数ConsumeElementTSF中使用napi_call_threadsafe_function将异步回调处理函数call_js_cb抛到EventLoop中,等待调度执行。

MultiThreads.cpp文件

   
  1. // thread safe function async interface
  2. static napi_value GetImagePathAsyncTSF(napi_env env, napi_callback_info info) {
  3. size_t paraNum = 2;
  4. napi_value paraArray[2] = {nullptr};
  5. // parse parameters
  6. napi_status operStatus = napi_get_cb_info(env, info, &paraNum, paraArray, nullptr, nullptr);
  7. if (operStatus != napi_ok) {
  8. return nullptr;
  9. }
  10. napi_valuetype paraDataType = napi_undefined;
  11. operStatus = napi_typeof(env, paraArray[0], &paraDataType);
  12. if ((operStatus != napi_ok) || (paraDataType != napi_string)) {
  13. return nullptr;
  14. }
  15. operStatus = napi_typeof(env, paraArray[1], &paraDataType);
  16. if ((operStatus != napi_ok) || (paraDataType != napi_function)) {
  17. return nullptr;
  18. }
  19. // napi_value convert to char *
  20. constexpr size_t buffSize = 100;
  21. char strBuff[buffSize]{}; // char buffer for imageName string
  22. size_t strLength = 0;
  23. operStatus = napi_get_value_string_utf8(env, paraArray[0], strBuff, buffSize, &strLength);
  24. if ((operStatus != napi_ok) || (strLength == 0)) {
  25. return nullptr;
  26. }
  27. // async resource
  28. napi_value asyncName = nullptr;
  29. string asyncStr = "async napi_threadsafe_function";
  30. operStatus = napi_create_string_utf8(env, asyncStr.c_str(), asyncStr.length(), &asyncName);
  31. if (operStatus != napi_ok) {
  32. return nullptr;
  33. }
  34. // defines context data. the memory will be released in CompleteFunc
  35. auto contextData = new ContextData;
  36. contextData->args = strBuff;
  37. // create thread safe function
  38. if (tsFun == nullptr) {
  39. operStatus =
  40. napi_create_threadsafe_function(env, paraArray[1], nullptr, asyncName, MAX_MSG_QUEUE_SIZE,
  41. INITIAL_THREAD_COUNT, nullptr, nullptr, nullptr, CallJsFunction, &tsFun);
  42. if (operStatus != napi_ok) {
  43. DeleteContext(env, contextData);
  44. return nullptr;
  45. }
  46. }
  47. // create producer thread
  48. thread producer(ProductElement, static_cast<void *>(contextData));
  49. producer.detach(); // must be detached
  50. // create consumer thread
  51. thread consumer(ConsumeElementTSF, static_cast<void *>(contextData));
  52. consumer.detach();
  53. return nullptr;
  54. }

参考链接

示例代码

标签:Node,异步,ArkTS,nullptr,HarmonyOS,API,线程,env,napi
From: https://www.cnblogs.com/strengthen/p/18504462

相关文章

  • 【Vue 3】全面解析Composition API的实战技巧
    ......
  • Node.js如何处理并发连接?
    Node.js如何处理并发连接?在现代web开发中,处理并发连接是一个对于构建高性能服务器至关重要的话题。Node.js是一个使用JavaScript作为编程语言的服务器端环境,内置非阻塞I/O模型,非常适合处理并发连接。在这篇博客中,我们将深入探讨Node.js如何有效地管理并发连接,并......
  • 《漫威蜘蛛侠2》steam_api64.dll缺少怎么办,解决步骤一览
    当在《漫威蜘蛛侠2》中遇到提示缺少steam_api64.dll文件的问题时,可以按照以下步骤进行解决:DirectX修复工具下载地址:https://dll.sly99.cn/download/DirectX_c11_t20555413.exehttps://dll.sly99.cn/download/DirectX_c11_t20555413.exe一、验证游戏文件完整性打开Steam客......
  • HarmonyOS:Node-API典型场景开发(1)
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤博客园地址:为敢技术(https://www.cnblogs.com/strengthen/ )➤GitHub地址:https://github.com/strengthen➤原文地址:https://www.cnblogs.com/strengthen/p/18504101➤如果链接不是为敢技术的博客园地址,则可能是......
  • 打造优雅API接口的黄金法则,让后端开发更高效
    在当今技术日益复杂、业务需求快速增长的背景下,应用系统不仅要满足功能需求,还要确保与其他系统、第三方平台及服务的无缝对接。在这样的复杂环境中,API接口就像是系统的“桥梁”,负责高效、可靠地传递信息,帮助实现跨系统的协同工作。然而,一个不优雅的API接口设计可能会带来......
  • Linux系统安装Nodejs的详细教程
    Linux系统安装Nodejs(详细教程)介绍:​Node.js发布于2009年5月,由RyanDahl开发,是一个基于ChromeV8引擎的JavaScript运行环境,使用了一个事件驱动、非阻塞式I/O模型,[1]让JavaScript运行在服务端的开发平台,它让JavaScript成为与PHP、Python、Perl、Ruby等服务端语言平起平坐的脚......
  • 三周精通FastAPI:14 表单数据和表单模型Form Models
     官网文档:表单数据-FastAPI表单数据¶接收的不是JSON,而是表单字段时,要使用 Form表单。fromfastapiimportFastAPI,Formapp=FastAPI()@app.post("/login/")asyncdeflogin(username:str=Form(),password:str=Form()):return{"username":user......
  • 三周精通FastAPI:8 请求体 - 多个参数、字段、嵌套模型
    本节内容对应FastAPI手册的三节,分别是请求体-多个参数,请求体-字段和请求体-嵌套模型。手册: https://fastapi.tiangolo.com/zh/tutorial/body-multiple-params/源代码示例是python3.10及以上版本。请求体-多个参数¶既然我们已经知道了如何使用 Path 和 Query,下面让......
  • 三周精通FastAPI:10 Cookie 参数 和Cookie 参数模型
    官方文档:Cookie参数-FastAPICookie参数¶定义 Cookie 参数与定义 Query 和 Path 参数一样。源码:fromtypingimportAnnotatedfromfastapiimportCookie,FastAPIapp=FastAPI()@app.get("/items/")asyncdefread_items(ads_id:Annotated[str|Non......
  • HarmonyOS:Node-API实现跨语言交互(3)使用Node-API实现跨语言交互开发流程
    ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤博客园地址:为敢技术(https://www.cnblogs.com/strengthen/ )➤GitHub地址:https://github.com/strengthen➤原文地址:https://www.cnblogs.com/strengthen/p/18504008➤如果链接不是为敢技术的博客园地址,则可能是......