您不需要使用uv_queue_work,但LibUV的线程库的一部分是uv_async_ *方法,这是您在这种情况下理想的方法.初始化辅助线程时,还要执行uv_async_init以创建共享异步数据结构.此函数也通过回调调用,该回调将在您的其他线程发送消息时运行.该回调是您调用JS代码来触发事件的地方.
这里有一些半假的代码作为例子:
在你的线程init函数中从JS调用,带有一个回调arg:
void ThreadInit(const v8::Arguments &args){
// This is just an example, this should be saved somewhere that
// some_callback will be able to access it.
v8::Persistent<:function> js_callback = args[0].As();
// And save this where you'll be able to call uv_close on it.
uv_async_t async_data;
uv_async_init(uv_default_loop(), &async_data, some_callback);
// initialize the thread and pass it async_data
}
在线程中:
async_data.data = (void*) // Some data structure...
uv_async_send(&async_data);
在线程回调中:
void some_callback(uv_async_t *async_data){
// Note that this depending on the data, you could easily get thread-safety issues
// here, so keep in mind that you should follow standard processes here.
void* data = async_data->data;
// Process that data however you need to in order to create a JS value, e.g.
// Using NanNew because it is more readable than standard V8.
v8::Local count = NanNew(data.count);
v8::Local<:value> argv[] = {
count
};
js_callback->Call(NanNull(), 1, argv);
}