Huy's Notes
Threads in WebAssembly

Threads in WebAssembly


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 pthread.

Or using Origin Trial to enable the features right on your user's browser, by a token attached to your domain.

How to use?

To use, just write your program as normal, then when you compile, supply the USE_PTHREADS and PTHREAD_POOL_SIZE into emcc command:

emcc -O2 -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=2 -o test.js test.c

Under the hood

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:

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:

Referred in

If you think this note resonated, be it positive or negative, please feel free to send me an email and we can talk.