Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 619
adam Avatar asked Aug 16 '16 11:08

adam


People also ask

How do you pass a callback function in JavaScript?

Passing a function to another function or passing a function inside another function is known as a Callback Function. Syntax: function geekOne(z) { alert(z); } function geekTwo(a, callback) { callback(a); } prevfn(2, newfn); Above is an example of a callback variable in JavaScript function.

What is true about a callback function?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Which of the following is a true statement for JavaScript callbacks?

Which of the following is a true statement for JavaScript callbacks? All except None. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. A callback is a plain JavaScript function passed to some method as an argument or option.

Why do we use callback function in JavaScript?

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.


1 Answers

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
like image 145
adam Avatar answered Oct 13 '22 19:10

adam