Skip to content

Pthreads with WebAssembly

Derek Schuff edited this page Nov 15, 2018 · 18 revisions

NOTE: Due to the recent Spectre vulnerabilities, browsers other than Chrome have disabled SharedArrayBuffer by default. Eventually that should get fixed, but meanwhile you must enable pthreads manually to test, and probably should not do that in a non-test environment.

Emscripten has support for compiling with pthreads, using asm.js, Web Workers, and SharedArrayBuffer. That support is documented here with information about porting and differences from other pthread-supporting platforms. WebAssembly has a proposed spec for threads (or more properly, for a shared linear memory and atomic memory instructions), with an overview here and spec here. This spec has experimental implementations in Firefox Nightly and Chrome Canary.

Emscripten now also has experimental support for the wasm threading spec. Currently you need to use the head of the incoming branch of emscripten. To build a simple threaded program: emcc program.c -s USE_PTHREADS=1 -s WASM=1 -o program.html (it may also be desirable to use -s PTHREAD_POOL_SIZE as documented in the emscripten threading doc).

To test with Chrome Canary, use the following flags: --js-flags=--experimental-wasm-threads --enable-features=WebAssembly,SharedArrayBuffer. These can alternatively be enabled/disabled in chrome://flags/#enable-webassembly-threads as "WebAssembly threads support". In Firefox nightly, SharedArrayBuffer can be enabled in about:config by setting the javascript.options.shared_memory preference to true.

Using pthreads also currently forces use of a memory initializer file (e.g. as if you had specified --memory-init-file 1 in an asm.js build) instead of using the data section of the wasm file.