Rust/wasm32 webworker parallelism/messaging primitives?

The following works:

  • compiling Rust to wasm32
  • running multiple instances of Rust/wasm32, via web workers
  • communicating via postMessage, onmessage

Unfortunately, dealing with postMessage/onMessage callback hell is not very pleasant. I am missing things like: rayon par_iter(), mpsc::channel, async io.

Question: are there any crates for making Rust/wasm32 webworker messaging more pleasant ?

You could use GitHub - GoogleChromeLabs/wasm-bindgen-rayon: An adapter for enabling Rayon-based concurrency on the Web with WebAssembly. if you enable the atomics target feature to use rayon on wasm. (make sure to use -Zbuild-std as the standard library must be recompiled to ensure that the single threaded stub implementations of all concurrency primitives aren't used.) You will have to spawn new threads through rayon in that case. std::thread::spawn is still a panicking stub implementation. Mpsc::channel should work too. Note that javascript doesn't allow blocking on the main thread though, only on web workers, so you can't use locks or blocking mpsc receives on the main thread. As for async io, you will have to use async rust with the wasm-bindgen-futures crate to convert javascript Promises into rust Futures. It is not possible to block on Promises to resolve AFAIK.

1 Like

Also note that you need to use the right cross-origin isolation policy if you want to use wasm-bindgen-rayon or any other way to have shared memory between threads.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.