简体   繁体   English

将 JavaScript 回调传递给在另一个线程中调用它的 FFI 函数是否安全?

[英]Is it safe to pass a JavaScript callback to an FFI function which calls it in another thread?

I have a C function which takes a callback and invokes it on another thread:我有一个 C 函数,它接受一个回调并在另一个线程上调用它:

void call_in_new_thread(void (*callback)()) {
    // spawn a new thread and call `callback` in it ...
}

I want to call this function from JavaScript via Node-FFI, passing a JavaScript function to it:我想通过 Node-FFI 从 JavaScript 调用这个函数,向它传递一个 JavaScript 函数:

var callbackType = 'pointer'
var lib = ffi.Library('mylib', {
    'call_in_new_thread': [ 'void', [ callbackType ] ],
})   

var callback = ffi.Callback('void', [ 'void' ], function() {
    // which thread I'm in now?
    console.log("hello!")
})

lib.call_in_new_thread(callback)

Is this valid?这是有效的吗? Is it thread safe?它是线程安全的吗? Which thread does the JavaScript callback actually execute in: the Node.js main thread, or in the thread created by the FFI library? JavaScript 回调实际在哪个线程中执行:Node.js 主线程,还是 FFI 库创建的线程? Does Node-FFI synchronize the call somehow? Node-FFI 是否以某种方式同步呼叫?

I hacked together a quick demo to test this out .我编写了一个快速演示来测试这一点 It's using Rust instead of C for the native part, but that should be equivalent as Rust can compile to a normal shared library.它使用 Rust 而不是 C 作为本机部分,但这应该等同于 Rust 可以编译为普通共享库。

After running the demo, I would answer my own questions like this:运行演示后,我会像这样回答我自己的问题:

  • Yes, it seems to be valid and safe是的,它似乎有效且安全
  • The JavaScript callback gets executed in the main thread JavaScript 回调在主线程中执行
  • Node-FFI seems to handle the synchronization by pushing the JavaScript callback to a queue which gets popped on the main thread Node-FFI 似乎通过将 JavaScript 回调推送到在主线程上弹出的队列来处理同步

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM