Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

node.js - 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:

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:

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? Does Node-FFI synchronize the call somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • Yes, it seems to be valid and safe
  • The JavaScript callback gets executed in the main thread
  • Node-FFI seems to handle the synchronization by pushing the JavaScript callback to a queue which gets popped on the main thread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...