skip to content

A Rust image filter built for `wasm32-unknown-unknown` splits work with `std::thread::spawn`; why does calling it end in a `RuntimeError: unreachable` trap, and what can you do instead?

level: seniorimportance: nice to knowfreq 20%

answer

  1. std compiles, the OS is missing
  2. spawn unwraps an Unsupported error
  3. abort becomes the unreachable instruction
  4. a hook forwards the lost message
  5. workers are separate instances

basics

~20 s

On wasm32-unknown-unknown std compiles but cannot create threads: thread::spawn panics, and since the target aborts on panic, the module executes unreachable with no message. thread::Builder::spawn returns an Unsupported error instead, which allows a single-threaded fallback.

solid answer

~40 s

This target's std compiles every API, but OS-backed functions are stubs. `thread::Builder::spawn` returns an `io::Error` of kind `Unsupported`; `thread::spawn` unwraps that and panics, as does `std::time::Instant::now`, while `std::fs` returns errors and `println!` prints nothing. The target is compiled with `panic=abort`, so a panic ends in WebAssembly's `unreachable` instruction, which the JavaScript engine raises as a `RuntimeError`; the message is lost unless a hook installed with `std::panic::set_hook` forwards it, for example to `web_sys::console::error_1`. Options: detect the error with `Builder::spawn` and run the work on the calling thread in chunks; run the filter in Web Workers, each a separate instance with its own memory, exchanging copies of the data; or use shared-memory threads, which need the `atomics` target feature and a std rebuilt on nightly. For WASI hosts, `wasm32-wasip1-threads` exists.

code

rust · 34 lines
rust
use std::thread;

fn invert(rows: &mut [u8]) {
    for b in rows {
        *b = 255 - *b;
    }
}

/// Inverts a buffer on a worker thread, or on the caller's thread when the
/// target cannot spawn one. Returns 1 if a thread ran the work, 0 otherwise.
#[unsafe(no_mangle)]
pub extern "C" fn invert_all(ptr: *mut u8, len: usize) -> u32 {
    // SAFETY: the host passes a buffer of `len` bytes in this module's memory.
    let pixels = unsafe { std::slice::from_raw_parts_mut(ptr, len) };
    let spawned = thread::scope(|s| {
        match thread::Builder::new().spawn_scoped(s, || invert(pixels)) {
            Ok(_) => true,
            Err(e) => {
                // On wasm32-unknown-unknown this is ErrorKind::Unsupported.
                assert_eq!(e.kind(), std::io::ErrorKind::Unsupported);
                false
            }
        }
    });
    if !spawned {
        invert(pixels);
    }
    spawned as u32
}

#[unsafe(no_mangle)]
pub extern "C" fn spawn_or_trap() -> u32 {
    thread::spawn(|| 2 + 2).join().unwrap()
}

go deeper

for a junior

Recall that std code compiles for wasm32-unknown-unknown even where it cannot run, and that thread::spawn is one of the calls that fails there.

for a middle

Explain the chain: Builder::spawn returns Unsupported, thread::spawn turns it into a panic, and abort on wasm becomes an unreachable trap without a message.

for a senior

Show the production fixes: a panic hook forwarding to console.error, a Builder::spawn fallback, and a clear account of what workers and shared-memory threads each cost.

for a principal

Weigh whether a filter library should support shared-memory threads at all, given the nightly toolchain and page requirements, against chunked single-threaded work.

## std compiles, the operating system is missing `wasm32-unknown-unknown` ships the full standard library, so code that uses `std::thread`, `std::time` or `std::fs` **compiles**. The platform documentation is explicit that many of those functions cannot work, because the target imports nothing from its host. A module built from std alone has no imports at all, so it cannot reach a clock, a file system or a thread API. What each stub does, as observed with rustc 1.99.1 and Node: | Call on `wasm32-unknown-unknown` | Result | |---|---| | `thread::Builder::new().spawn(..)` | `Err`, `io::ErrorKind::Unsupported` | | `thread::spawn(..)` | panics | | `std::time::Instant::now()` | panics | | `std::fs::read(..)` | `Err`, `io::ErrorKind::Unsupported` | | `println!` | prints nothing | `thread::spawn` is literally `Builder::new().spawn(f).expect("failed to spawn thread")` in std's source: it turns the `Unsupported` error into a panic, which is why the filter fails at run time rather than at compile time. ## From panic to `unreachable` Rust's wasm targets compile with **`panic=abort`**. Aborting on WebAssembly means executing the `unreachable` instruction, which **traps**: the engine stops the call and throws a `RuntimeError` into JavaScript, worded "RuntimeError: unreachable" in Node. Two things are lost: - the panic message, since std has nowhere to print it on this target; - any chance to recover inside Rust, because `catch_unwind` cannot catch an abort. A **panic hook** restores the message. `std::panic::set_hook` runs before the abort, and a hook that calls `web_sys::console::error_1` puts the text in the browser console. Installing it from a `#[wasm_bindgen(start)]` function runs it once, when the generated glue instantiates the module. How hooks and the two panic strategies work in general belongs to the panics material. ## Option 1: detect and fall back Use `thread::Builder::spawn` (or `spawn_scoped` inside `thread::scope`) and handle the error. The example below inverts the pixels on a worker thread where one can be spawned, and on the calling thread where the target cannot; on `wasm32-unknown-unknown` it returns 0 and still inverts the buffer. For long filters, process the image in chunks so the page can return to its event loop between calls. ## Option 2: Web Workers as separate instances A **Web Worker** runs JavaScript on another thread, and each worker can instantiate its own copy of the module. Those instances have **separate linear memories**: work is split by posting copies of pixel ranges to each worker and copying results back. No Rust code changes, but data is copied, and no `Arc` or `Mutex` spans instances. Worker setup itself is browser-platform material. ## Option 3: shared-memory threads Real threads sharing one memory require the WebAssembly **`atomics`** feature. It is not in the target's default features (`rustc --print cfg` lists `bulk-memory`, `multivalue` and `reference-types`, not `atomics`), and the prebuilt std is compiled without it, so this path means: 1. a nightly toolchain rebuilding std with atomics enabled (unstable `-Zbuild-std`); 2. wasm-bindgen's atomics support, which itself enables nightly-only features; 3. a page allowed to share memory between workers. That is a significant commitment for a library; most filters ship single-threaded or with independent workers. ## Diagnosing the trap A bare `RuntimeError: unreachable` says only that the module trapped. A short routine finds the cause: 1. install the console panic hook, rebuild and repeat the action, so the panic message and source location appear; 2. if the message reads "failed to spawn thread", the code called `thread::spawn`, directly or inside a dependency; 3. search the dependency tree for thread pools or timers, which call `thread::spawn` or `Instant::now` internally; 4. replace the call with `Builder::spawn` and a fallback, or gate the threaded path with `cfg` so the browser build never compiles it. Even without the hook, the JavaScript error's stack lists mangled Rust function names, `__rust_start_panic` and `panic_with_hook` among them, when the module keeps its `name` section; a module built with `strip = true` shows only `wasm-function[39]`-style indices. ## Outside the browser On WASI, `wasm32-wasip1` also cannot spawn: `Builder::spawn` returns an error and `thread::spawn` panics, with the message printed to stderr this time. The separate `wasm32-wasip1-threads` target supports threads for runtimes that implement them. Thread APIs themselves, `scope`, `JoinHandle` and `Builder`, belong to the material on spawning threads.

  • Why can `std::panic::catch_unwind` not turn the trap into a Rust error on this target?
    `catch_unwind` catches panics that unwind, and Rust's wasm targets compile with `panic=abort`, so a panic never unwinds: it runs the hook and then executes `unreachable`. Unwinding on wasm needs `-C panic=unwind` with a std rebuilt on nightly. The practical fix is to avoid the panic: use `Builder::spawn` and handle its `Unsupported` error.
  • What does splitting the filter across Web Workers cost compared with native threads?
    Each worker instantiates its own module with its own linear memory, so pixel ranges are copied to the workers and results copied back, and nothing like an `Arc<Mutex<T>>` spans them. Shared-memory threads avoid the copies but need the `atomics` target feature, a std rebuilt on nightly and wasm-bindgen's atomics support, so most crates accept the copies.

  • `std::thread::spawn` fails to compile for `wasm32-unknown-unknown`.
  • The panic message appears in the browser console without any setup.
  • Setting `panic = "unwind"` in Cargo.toml lets JavaScript catch the panic.
  • Web Workers running the module share one Rust heap, so a `Vec` needs no copying.
  • `std::time::Instant::now` works on every wasm32 target.