Starting from Chrome 70, there's a
pthread support added, you can enable it in
chrome://flags screen. At the time of writing, there's only Chrome that support
Or using Origin Trial to enable the features right on your user's browser, by a token attached to your domain.
To use, just write your program as normal, then when you compile, supply the
emcc -O2 -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=2 -o test.js test.c
Browsers already has support for thread via Web Workers, but they do not share mutable data between them, they relying on message passing for communication.
Side note: Message passing with Web Workers has a big performance impact: https://www.loxodrome.io/post/web-worker-performance/
WebAssembly threads can share data between threads, the shared memory implemented using
SharedArrayBuffer. Each thread in the thread pool runs in a Web Worker. That's why we supply the
PTHREAD_POOL_SIZE in the compile step.
Make sure thread pool size is equals to the maximum number of threads your application needs, or thread creation may fail. But don't make it too large, you'll create unnecessary Web Workers that do nothing, but still using memory.
Question: I heard that
SharedArrayBuffer is disabled due to the Spectre and Meltdown, then what will happen to WebAssembly Threads?
Answer: The vulnerabilities will be fixed eventually, then browsers will start shipping with
SharedArrayBuffer enabled by default again, everything should be fine. In the meantime, we can just enable it ourselves.
Bonus: A great article about how Rust implemented thread support for WebAssembly thru
wasm-bindgen, they even have a working demo but there are still so many works to do: https://rustwasm.github.io/2018/10/24/multithreading-rust-and-wasm.html
Welcome! Look like you've found my personal notebook. This is the place where you can take a peek into my mind to see what I've been…
If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.