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

时间:2022-09-25 21:01:25

Say 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 ...
}

Now 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)

My questions: Is it valid? Is it thread safe? Which thread does the javascript callback actually execute in? In the node.js main thread, or in the thread created by the ffi library? Does Node-FFI synchronize the call somehow?

我的问题:它有效吗?它是线程安全吗? javascript回调实际执行哪个线程?在node.js主线程中,还是在ffi库创建的线程中? Node-FFI会以某种方式同步呼叫吗?

1 个解决方案

#1


4  

Hacked together a quick demo to test this out: https://github.com/madadam/rust_ffi_async_demo. (using rust, not C for the native part, but that should be equivalent as rust can build to normal shared library).

将一个快速演示集成在一起以测试它:https://github.com/madadam/rust_ffi_async_demo。 (使用rust,而不是C作为原生部分,但这应该等同于rust可以构建到普通的共享库)。

So, after running the demo, I would answer my own questions like this:

所以,在运行演示之后,我会像这样回答我自己的问题:

  • Yes, it seems to be valid and safe
  • 是的,它似乎是有效和安全的

  • The js callback gets executed in the main thread
  • js回调在主线程中执行

  • Node-FFI seems to handle the synchronization by pushing the js callback to a queue which gets popped on the main thread.
  • Node-FFI似乎通过将js回调推送到主线程上弹出的队列来处理同步。

#1


4  

Hacked together a quick demo to test this out: https://github.com/madadam/rust_ffi_async_demo. (using rust, not C for the native part, but that should be equivalent as rust can build to normal shared library).

将一个快速演示集成在一起以测试它:https://github.com/madadam/rust_ffi_async_demo。 (使用rust,而不是C作为原生部分,但这应该等同于rust可以构建到普通的共享库)。

So, after running the demo, I would answer my own questions like this:

所以,在运行演示之后,我会像这样回答我自己的问题:

  • Yes, it seems to be valid and safe
  • 是的,它似乎是有效和安全的

  • The js callback gets executed in the main thread
  • js回调在主线程中执行

  • Node-FFI seems to handle the synchronization by pushing the js callback to a queue which gets popped on the main thread.
  • Node-FFI似乎通过将js回调推送到主线程上弹出的队列来处理同步。