本文介绍了将js回调传递给在另一个线程中调用它的ffi函数是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个C函数,它接受一个回调并在另一个线程上调用它:

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

现在我想通过Node-FFI从javascript调用此函数,将javascript函数传递给它:

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)

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

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?

推荐答案

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

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:


  • 是的,似乎是有效且安全的

  • js回调在主线程中执行

  • Node-FFI似乎处理通过将js回调推送到主线程上弹出的队列来实现同步。

这篇关于将js回调传递给在另一个线程中调用它的ffi函数是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 13:40