chemicstry / wasm_thread

A rust `std::thread` replacement for wasm32 target
Apache License 2.0
123 stars 16 forks source link

wasm_thread

License Cargo Documentation

An std::thread replacement for wasm32 target.

This crate tries to closely replicate std::thread API. Namely, it doesn't require you to bundle worker scripts and resolves wasm-bindgen shim URL automatically.

Note that some API is still missing and may be even impossible to implement given wasm limitations.

Using as a library

Notes on wasm limitations

Alternatives

For a higher-level threading solution, see wasm-bindgen-rayon, which allows one to utilize a fixed-size threadpool in web browsers.

Running examples

Simple

Native

wasm-bindgen

wasm-pack

Example output

Native:

hi number 1 from the spawned thread ThreadId(2)!
hi number 1 from the main thread ThreadId(1)!
hi number 1 from the spawned thread ThreadId(3)!
hi number 2 from the main thread ThreadId(1)!
hi number 2 from the spawned thread ThreadId(2)!
hi number 2 from the spawned thread ThreadId(3)!

Wasm:

hi number 1 from the main thread ThreadId(1)!
hi number 2 from the main thread ThreadId(1)!
hi number 1 from the spawned thread ThreadId(2)!
hi number 1 from the spawned thread ThreadId(3)!
hi number 2 from the spawned thread ThreadId(2)!
hi number 2 from the spawned thread ThreadId(3)!

As you can see wasm threads are only spawned after main() returns, because browser event loop cannot continue while main thread is blocked.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.