Is it safe to pass js callback to a ffi function which calls it in another thread?

爱⌒轻易说出口 提交于 2019-12-05 23:33:19

问题


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

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

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?


回答1:


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

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
  • Node-FFI seems to handle the synchronization by pushing the js callback to a queue which gets popped on the main thread.


来源:https://stackoverflow.com/questions/38973254/is-it-safe-to-pass-js-callback-to-a-ffi-function-which-calls-it-in-another-threa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!