Node.js C ++插件:来自不同线程的多个回调 [英] Node.js C++ addon: Multiple callbacks from different thread

查看:83
本文介绍了Node.js C ++插件:来自不同线程的多个回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个节点C ++插件,该插件应调用js函数,因为事件是由其他不受我控制的线程触发的(实际上是我使用的托管dll的.net线程).由于JS世界是单线程的,所以我不能只是保留js函数引用并从该非js线程调用它.我什至无法在该线程上创建要传递给该回调函数的参数.

I'm creating a node C++ addon that is supposed to call back a js function as events are triggered by some other thread that is not under my control (it is actually a .net thread from a managed dll I use). As the JS world is single-threaded, I can't just keep the js function reference around and call it from that non-js thread. I can't even create the parameters I want to pass to that callback function on that thread.

我已经看到uv_queue_work在需要将工作移出js线程的情况下使用,一旦完成并从js线程中调回来做您需要在其上做的任何事情,例如回调一个js函数.

I've seen uv_queue_work being used in cases where you want to move work off of the js thread and once finished and get called back from the js thread to do whatever you need to do on it, like e.g. calling back a js function.

供以后参考,以下是该函数的签名:

For later reference, here's that function's signature:

int uv_queue_work(uv_loop_t* loop, uv_work_t* req, uv_work_cb work_cb,
uv_after_work_cb after_work_cb);

调用uv_queue_work对于一次性工作很好,我可以通过链接从after_work_cbuv_queue_work的调用来任意频繁地打电话给我,而work_cb与该其他线程同步,但是我想知道是否没有比这更直接的方法了.

Calling uv_queue_work is fine for one-off jobs, and I could probably get it to call me arbitrarily often by chaining calls to uv_queue_work from after_work_cb, while work_cb synchronizes with that other thread, but I wonder if there isn't a more straightforward way to do it.

就像node.js提供的fn一样,其他任何线程都可以使用fn指针直接调用该fn,该指针指向下一次在主js线程上执行的代码.有什么主意吗?

Like a fn provided by node.js that could be called directly by any other thread with a fn pointer that points to code to be executed on the main js thread at the next occasion. Any idea?

推荐答案

而不是使用uv_queue_work,您应该查看uv_async_ *函数(查看

Rather than using uv_queue_work, you should look at the uv_async_* functions (Check out https://github.com/joyent/libuv/blob/master/include/uv.h).

可以在节点sqllite项目 https:/中找到一个很好的实现/github.com/developmentseed/node-sqlite3/blob/master/src/async.h .

A very nice implementation of this can be found in the node sqllite project https://github.com/developmentseed/node-sqlite3/blob/master/src/async.h.

不过,请注意,如果您对这些内容不熟悉,可能会遇到一些 TERRIBLE 循环引用计数错误(应用程序退出的时间过早,或者完全没有

Just a note however, if you are not EXTREMELY careful with this stuff, you will end up with some TERRIBLE loop reference count bugs (Application exits to early, or not at all)

这篇关于Node.js C ++插件:来自不同线程的多个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆