要在其他线程中调用保存在vector中的Local,需要注意以下几点:

  1. 确保在主线程中创建和保存Local对象,因为Node.js的V8引擎只能在主线程中使用。

  2. 在其他线程中调用Local对象时,需要使用uv_async_send函数来通知主线程执行回调函数。

  3. 在主线程中,需要使用uv_async_init函数初始化一个async handle,并使用uv_async_send函数来触发回调函数的执行。

下面是一个示例代码,演示如何保存和调用Local对象:

#include <uv.h>
#include <vector>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>

#include <node.h>
#include <node_buffer.h>

using namespace v8;

std::vector<Local<Function>> callbacks;
std::mutex mutex;
std::condition_variable cv;

void async_callback(uv_async_t* handle)
{
    std::unique_lock<std::mutex> lock(mutex);

    while (!callbacks.empty())
    {
        Local<Function> callback = callbacks.back();
        callbacks.pop_back();

        lock.unlock();

        callback->Call(Null(isolate), 0, nullptr);

        lock.lock();
    }

    cv.notify_all();
}

void thread_func()
{
    std::this_thread::sleep_for(std::chrono::seconds(5)); // simulate some work

    std::unique_lock<std::mutex> lock(mutex);
    callbacks.emplace_back(isolate, Local<Function>::Cast(args[0]));
    lock.unlock();

    uv_async_send(&async_handle);

    lock.lock();
    cv.wait(lock);
    lock.unlock();
}

void start_thread(const FunctionCallbackInfo<Value>& args)
{
    std::thread t(thread_func);
    t.detach();
}

void init(Handle<Object> exports)
{
    NODE_SET_METHOD(exports, "startThread", start_thread);

    uv_async_init(uv_default_loop(), &async_handle, async_callback);
}

NODE_MODULE(addon, init)

在这个示例中,线程函数thread_func模拟一些工作,并将Local对象保存在callbacks vector中。然后,使用uv_async_send函数来通知主线程执行回调函数。

在主线程中,使用uv_async_init函数初始化一个async handle,并将其传递给uv_async_send函数。当uv_async_send函数被调用时,async_callback函数将被触发,在其中执行callbacks vector中保存的所有回调函数。在执行回调函数之前,需要使用互斥锁来确保线程安全。在执行完回调函数之后,使用条件变量来通知等待的线程

nodejs c++ 保存LocalFunction在vector 在其他线程里调用

原文地址: http://www.cveoy.top/t/topic/fI7T 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录