WebAssembly Threading: Pthreads, Workers, or Single-Thread
Decide when to enable Emscripten pthreads with SharedArrayBuffer versus Web Workers or single-threaded wasm, including the required COOP and COEP headers.
20 Nov 2025, 03:47 UTC

Start with the constraint, not the feature
WebAssembly modules run on a single thread by default. If your module needs to saturate multiple CPU cores, the shared-memory option is Emscripten pthreads built on SharedArrayBuffer and the Atomics API. Browsers block SharedArrayBuffer unless the document is cross-origin isolated, which means the server must send Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers. If you cannot change those headers, shared-memory threads are not an option.
Use this guide when you control the origin serving the wasm module, the computation is coarse-grained enough to amortize thread startup, and you can measure real wall-clock time on target devices.
Compare the three deployment patterns
| Pattern | Shared memory | Header requirement | Memory model | Best suited for |
|---|---|---|---|---|
| Single-threaded wasm | No | None | One linear memory, one thread | Lightweight modules, UI work, headers impossible |
| Emscripten pthreads | Yes, via SharedArrayBuffer | COOP same-origin + COEP require-corp | One linear memory shared by a pthread pool | Compute-heavy kernels, image or audio processing, physics |
| Web Workers with separate wasm instances | No, message passing only | None | Each worker duplicates wasm linear memory | Embarrassingly parallel tasks, no header control |
Trade-offs that determine the choice
- Header side effects. COEP require-corp blocks cross-origin subresources—iframes, scripts, images—unless they opt in with Cross-Origin-Resource-Policy or are served credentialless. Enabling these headers can break embedded third-party content.
- Pool size. Emscripten creates the pthread pool at startup. A pool larger than the device's CPU cores wastes memory and adds context-switch cost; a pool too small leaves cores idle.
- Granularity. Threads help coarse kernels. Fine-grained tasks with frequent Atomics synchronization can run slower than serial code because of pool startup and contention.
- Debugging. Browser DevTools support for stepping through multithreaded wasm is uneven, so race conditions are harder to reproduce than in single-threaded code.
Implementation: enable isolation and compile pthreads
This section changes server state and build artifacts. Roll back by removing the headers or restoring the previous server configuration, and by recompiling without -s USE_PTHREADS=1.
1. Serve cross-origin isolation headers
Run on the origin serving the wasm module. You need permission to edit server configuration, typically root or sudo access.
add_header Cross-Origin-Opener-Policy "same-origin" always; add_header Cross-Origin-Embedder-Policy "require-corp" always;
Expected check: curl -I https://example.com/ should list both headers. Replace example.com with your origin. Risk: cross-origin embeds on your pages may fail unless they carry appropriate opt-in headers.
2. Compile the kernel with Emscripten pthreads
Run in a terminal with the Emscripten SDK activated.
emcc -O3 -s USE_PTHREADS=1 -s PTHREAD_POOL_SIZE=4 -s MODULARIZE=1 -s EXPORT_NAME="ComputeKernel" kernel.c -o kernel.js
Placeholders: kernel.c is your C or C++ source; 4 should match the core count you plan to support, not an arbitrary maximum. Emscripten emits a main JavaScript file plus worker files that share one wasm linear memory.
3. Load and verify in the page
if (!window.crossOriginIsolated) {
console.warn("Cross-origin isolation missing; pthreads will fall back to serial execution.");
}
if (typeof SharedArrayBuffer === "undefined" || typeof Atomics === "undefined") {
console.warn("SharedArrayBuffer or Atomics is unavailable in this browser.");
}
import ComputeKernel from "./kernel.js";
const kernel = await ComputeKernel({
locateFile: (name) => name,
});
Where: browser console or page module. Permissions: none. Expected check: open DevTools Security panel and confirm the page reports cross-origin isolated; confirm both header values in the Network panel.
Validate the result without assuming speedup
- Compile the same source twice: once with
-s USE_PTHREADS=1and once without. - Measure
performance.now()around the compute entry point on representative desktop and mobile browsers. - Open the DevTools Performance thread track while the wasm module runs; additional worker threads should appear only in the pthreads build.
- If timings are equal or worse, the task is likely too fine-grained or the pool is oversized for the device.
Limitations
- SharedArrayBuffer is unavailable unless the origin sends both headers correctly, and older browser versions may block it entirely.
- PTHREAD_POOL_SIZE is static at compile time; tune it for the lowest common denominator of your target devices rather than your development machine.
- Web Workers avoid headers but duplicate memory and add serialization cost for every message.
Practical check
Paste this in the page console on the isolated origin:
console.log({
isolated: window.crossOriginIsolated,
sharedArrayBuffer: typeof SharedArrayBuffer,
atomics: typeof Atomics,
});
Expected result on a correctly configured origin: isolated is true and both APIs are present. If any value is false or undefined, do not load the pthreads build; serve the single-threaded fallback instead.