在 Node.js 插件中使用 std::thread

Using std::thread in Node.js Addon

假设我使用同步函数,来自我的 Node.js 插件:

var check_ok = addon.my_function(parameters);
var final_results = addon.final_function(parameters);

但是在方法代码中我有:

std::thread t[10]; //Global
//...
void my_function(const FunctionCallbackInfo<v8::Value>& args) {
//....
t[0] = thread(random_void_function, [parameters])
t[1] = thread(random_void_function_2, [parameters])
//...
}
//...
void final_results(const FunctionCallbackInfo<v8::Value>& args) {
//...
t[0].join();
t[1].join();
//...Give results.. etc
}

所以我有2个插件的同步调用,但是在这个插件中使用了两个线程。一个函数将启动线程,另一个函数将加入它们。问题是:random_void_functionrandom_void_function_2 将 运行 并行?由于my_functionfinal_function是同步的,所以random_void_functionrandom_void_function_2会阻塞事件循环吗?据我所知,他们没有阻止。

The questions are: random_void_function and random_void_function_2 will run in parallel?

是的,只要他们活得够久。如果它们是 short-lived,一个同样合理的结果是第一个在第二个开始和退出之前开始和退出(反之亦然)。

Since my_function and final_function are synchronous, the random_void_function and random_void_function_2 will block the event loop? From what I see, they not block.

不,也许。 addon.my_function 不会 阻塞事件循环。 addon.final_results(我假设你打算在上面调用而不是 addon.final_function)只会在 random_void_function 长期存在时阻塞。如果他们是短暂的并且已经退出,addon.final_results 将立即退出。

由于您没有看到任何阻塞,我怀疑 random_void_function 是 short-lived。