Question about https://github.com/rustwasm/wasm-bindgen/blob/main/examples/raytrace-parallel/src/pool.rs#L119

Link: wasm-bindgen/pool.rs at main · rustwasm/wasm-bindgen · GitHub

Signature:

fn execute(&self, f: impl FnOnce() + Send + 'static) -> Result<Worker, JsValue> {

Context: this is part of a small 'library' which allows rayon style parallelism with webworkers.

Question:

  1. Do these web workers share the same memory ?

  2. If not, how is passing around closures work?

  3. If so, how is the memory kept safe in light of multiple threads? All worker threads are limited to the same 2GB / 4GB of memory ?

As you can see, this method does the following:

  • boxes the passed closure;
  • converts the box to raw pointer;
  • sends the raw pointer to worker via post_message.

So, it seems that the memory is shared, since otherwise the pointer would be dangling after sending. And, indeed, when spawning a new worker thread, wasm_bindgen::memory is being sent there, which is the handler to global memory allocation.

1 Like