UP | HOME

Thread for WebAssembly

Table of Contents

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.

WasmThreads3.png

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

1 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

2 Under the hood

Browsers already has support for thread, they're called 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

Date: 2019-01-16 Wed 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41