Multi threading Rust/wasm32 in Chrome?

  1. This is a followup to Wasm32, multithreading (co-op is fine)?

  2. Crates.io has a webworker crate https://crates.io/crates/webworker , but it appears to be doing something else (server side).

  3. On x86_64, to start a read, I just do std::thread::spawn(|| { ... }).

Question: On rust/wasm32/Chrome, is there a crate that provides similar functionality? The way it would work under the hood would be to start a new worker, then load the wasm32 in that web worker, and provide some type of mspc channel for sending msgs back & forth.

It isn't all packaged up in a nice crate, but the wasm-bindgen guide has a chapter on running WebAssembly in a web worker.

1 Like

Cool, it looks like all the parts are there.

wasm_thread - Rust and wasm-bindgen/examples/raytrace-parallel at master · rustwasm/wasm-bindgen · GitHub also look interesting

From the doc you linked:

#[wasm_bindgen]
pub fn startup() {
    // Here, we create our worker. In a larger app, multiple callbacks should be
    // able to interact with the code in the worker. Therefore, we wrap it in
    // `Rc<RefCell>` following the interior mutability pattern. Here, it would
    // not be needed but we include the wrapping anyway as example.
    let worker_handle = Rc::new(RefCell::new(Worker::new("./worker.js").unwrap()));
    console::log_1(&"Created a new worker from within WASM".into());

    // Pass the worker to the function which sets up the `oninput` callback.
    setup_input_oninput_callback(worker_handle.clone());
}

This here, Worker::new looks like the std::thread::spawn right? It is calling worker.js, which goes back to JS land to setup a web worker then reload the wasm in that web worker.

Yeah, calling Worker::new() will spin off a web worker that executes a JavaScript script and gives you an object you can use to send messages to/from the worker.

I don't believe web workers let you execute WebAssemly modules directly so you'll need to write a glue script in JavaScript that imports your WebAssembly.

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.