将 JavaScript 回调传递给在另一个线程中调用它的 FFI 函数是否安全? [英] Is it safe to pass a JavaScript callback to an FFI function which calls it in another thread?
问题描述
我有一个 C 函数,它接受一个回调并在另一个线程上调用它:
I have a C function which takes a callback and invokes it on another thread:
void call_in_new_thread(void (*callback)()) {
// spawn a new thread and call `callback` in it ...
}
我想通过 Node-FFI 从 JavaScript 调用这个函数,向它传递一个 JavaScript 函数:
I want to call this function from JavaScript via Node-FFI, passing a JavaScript function to it:
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)
这有效吗?它是线程安全的吗?JavaScript 回调实际在哪个线程中执行:Node.js 主线程,还是 FFI 库创建的线程?Node-FFI 是否以某种方式同步调用?
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? Does Node-FFI synchronize the call somehow?
推荐答案
I hacked together 一个快速演示来测试这个出来.它在本机部分使用 Rust 而不是 C,但这应该等同于 Rust 可以编译为普通共享库.
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.
运行演示后,我会像这样回答我自己的问题:
After running the demo, I would answer my own questions like this:
- 是的,它似乎有效且安全
- JavaScript 回调在主线程中执行
- Node-FFI 似乎通过将 JavaScript 回调推送到在主线程上弹出的队列来处理同步
这篇关于将 JavaScript 回调传递给在另一个线程中调用它的 FFI 函数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!