问题
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