Crate web_thread

Crate web_thread 

Source
Expand description

§web-thread

A crate for long-running, shared-memory threads in a browser context for use with wasm-bindgen. Supports sending non-Send data across the boundary using postMessage and transfer.

§Requirements

Like all Web threading solutions, this crate requires Wasm atomics, bulk memory, and mutable globals:

.cargo/config.toml

[target.wasm32-unknown-unknown]
rustflags = [
    "-C", "target-feature=+atomics,+bulk-memory,+mutable-globals",
]

as well as cross-origin isolation on the serving Web page in order to enable the use of SharedArrayBuffer, i.e. the HTTP headers

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

The credentialless value for Cross-Origin-Embedder-Policy should also work, but at the time of writing is not supported in Safari.

§Linking the binary

Since this crate can’t know the location of your shim script and Wasm binary ahead of time, you must make the module identifier web-thread:wasm-shim resolve to the path of your wasm-bindgen shim script. This can be done with a bundler such as Vite or Webpack, or by using a source-transformation tool such as tsc-alias:

tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./",
        "paths": {
            "web-thread:wasm-shim": ["./src/wasm/my-library.js"]
        }
    },
    "tsc-alias": {
        "resolveFullPaths": true
    }
}

Turbopack is currently not supported due to an open issue when processing cyclic dependencies. See the following discussions for more information:

Structs§

SendTask
A Task with a Send output. See Thread::run_send for usage.
Task
A task that’s been spawned on a Thread.
Thread
A representation of a JavaScript thread (Web worker with shared memory).

Traits§

AsJs
An object-safe version of std::convert::TryInto/std::convert::TryFrom, relying on the JavaScript GC.
Post
Objects that can be sent via postMessage. A type that is Post supports being serialized into a JavaScript object that can be sent using postMessage, and also getting an array of subobjects that must be transferred.
PostExt
Convenience trait for something that can have messages posted to it, including transferables.

Type Aliases§

Error
The type of errors that can be thrown in the course of executing a thread.
Result