oven-sh / bun

Incredibly fast JavaScript runtime, bundler, test runner, and package manager – all in one
https://bun.sh
Other
73.95k stars 2.75k forks source link

Non blocking FFI #5490

Open robobun opened 1 year ago

robobun commented 1 year ago

Hi! How can I call FFI functions without blocking the main thread?

Library

#[no_mangle]
pub unsafe extern "C" fn listen(addr: *const c_char, cb: fn()) {
  loop {
    // Blocking code
  }
}

Bun

const { symbols: { listen } } = dlopen(`${import.meta.dir}/libexample.${suffix}`, {
  listen: {
    args: [FFIType.cstring],
    returns: FFIType.void,
  },
})

// That's what I'd like to do
await Promise.all([
  listen(...),
  listen(...),
  listen(...),
])

// Or
listen(...)

// Won't work until the `listen` function completes
setInterval(() => {
  console.log('Alive')
}, 1000)

The current behavior freezes the entire main thread of bun and I can't do anything else in bun while the listen function is running (infinitely).

Originally reported on Discord: Non blocking FFI

Pandapip1 commented 1 year ago

This feels more like a bug report than an enhancement to me. This is unexpected behaviour.

zebrapurring commented 1 year ago

With Node FFI this is implemented by using async to execute the function in a different thread. Is this behavior implemented in Bun aswell?

jackyzha0 commented 9 months ago

Hey, this is blocking us from adopting Bun in production at Replit :// ~Is async-ffi possible with napi? (e.g. https://github.com/napi-rs/napi-rs)~

ended up achieving non-blocking FFI with napi-rs + async

image

mefistofelix commented 2 months ago

Which is the eta or priority the bun team give to that?