A σ 2 blur of the Terrace Room photo takes 50 ms, and the laptop used in this lesson has 10 cores. The blur uses one of them. Threading splits one job across several threads that run at the same time, on different CPU cores. In the browser, those extra threads are Web Workers. A Worker can receive data in two ways: moved (transferred), or used together through a SharedArrayBuffer, with Atomics keeping them from overwriting each other.
The photo is cut into 4 long strips, and 4 of Mrs. Sri's helpers each work on one strip. First way: each helper carries their strip to their own table, then brings it back. Second way: everyone works at one big table, so nothing has to be carried around, but they need rules for taking turns, and the room has to be locked against strangers. The photo strips are slices of bytes, the own table is a transfer, the big table is a SharedArrayBuffer, the turn-taking rules are Atomics, and the room's lock is the COOP and COEP headers.
Worker: a second thread in the browser
A Worker runs its own JavaScript file on another thread. It cannot touch the DOM, and talks to the page through messages:
// worker.js: set up photolab.wasm once, then blur every strip it is sent
let x, base;
onmessage = (e) => {
const d = e.data;
if (d.bytes) {
x = new WebAssembly.Instance(new WebAssembly.Module(d.bytes)).exports;
base = x.memory.buffer.byteLength; // strips go after the module's initial memory
return;
}
const n = d.strip.byteLength, kernel = base + 2 * n;
const missing = kernel + 64 - x.memory.buffer.byteLength;
if (missing > 0) x.memory.grow(Math.ceil(missing / 65536));
new Uint8Array(x.memory.buffer).set(new Uint8Array(d.strip), base);
new Int32Array(x.memory.buffer, kernel, d.K.length).set(d.K);
x.blur_h(base, base + n, d.W, d.height, kernel, d.R);
x.blur_v(base + n, base, d.W, d.height, kernel, d.R);
const result = x.memory.buffer.slice(base + d.skip * d.W * 4, base + (d.skip + d.rows) * d.W * 4);
postMessage(result, [result]); // transfer: moved, not copied
};
postMessage(data, [buffer]): the second argument is a list of transferables. AnArrayBufferin that list moves to the other thread in almost no time, and on the sender's side its length becomes 0.- Each worker has its own Wasm instance, with its own memory. The functions are
blur_handblur_vfrom the lesson "Image Processing in the Browser". navigator.hardwareConcurrencygives the number of cores the browser reports: 10 in Chromium 147 on this laptop, 8 in WebKit 26.4 on the same laptop.
Splitting the photo into 4 strips
The photo is cut by rows: 800 rows become 4 × 200. The vertical blur needs 6 neighbouring rows above and below (r = 6 for σ 2), so each strip is sent with 6 extra rows on each side, and those extra rows are dropped from its result:
function blurStrips(n) {
const jobs = [];
for (let i = 0; i < n; i++) {
const y0 = Math.floor((H * i) / n), y1 = Math.floor((H * (i + 1)) / n);
const a = Math.max(0, y0 - R), b = Math.min(H, y1 + R); // plus 6 neighbouring rows
const strip = photo.slice(a * W * 4, b * W * 4).buffer;
jobs.push(new Promise((done) => {
workers[i].onmessage = (e) => done({ y0, data: new Uint8Array(e.data) });
workers[i].postMessage({ strip, height: b - a, skip: y0 - a, rows: y1 - y0, W, R, K }, [strip]);
}));
}
return Promise.all(jobs).then((parts) => {
const result = new Uint8Array(W * H * 4);
parts.forEach((p) => result.set(p.data, p.y0 * W * 4));
return result;
});
}
Before you look at the table, guess: the blur that takes 50 ms in one worker, split across 4 workers, takes how long? 12.5 ms, about 15 ms, or still 50 ms?
Measured on a MacBook M1 Pro (8 performance cores + 2 efficiency cores) busy running many other processes, the median of 5 rounds after a warm-up, on a page without isolation:
| σ 2 blur, 1200 × 800 | Chromium 147 | WebKit 26.4 |
|---|---|---|
| 1 worker | 50.2 ms | 49.0 ms |
| 2 workers | 26.0 ms (1.9×) | 25.0 ms (2.0×) |
| 4 workers | 15.1 ms (3.3×) | 14.0 ms (3.5×) |
The 4-worker result matches the 1-worker result byte for byte. Four workers give about 15 ms, not 12.5. The rest is the cost of copying the strips and the extra rows, sending messages, assembling the result, and cores busy with other processes.
For small jobs, the sums flip. The same JavaScript grayscale straight on the page: 1.88 ms in Chromium, 1.22 ms in WebKit. Through 4 workers: 1.62 ms and 1.52 ms. Almost no gain, and a loss in WebKit.
SharedArrayBuffer and Atomics
A SharedArrayBuffer is memory that several threads see at once: it is sent with postMessage, but neither moved nor copied. The trouble is that two threads can write the same place at the same time:
const counter = new Int32Array(new SharedArrayBuffer(4));
// in every worker, 4 workers at once, 1,000,000 times each:
counter[0]++; // read, add, write: they can overwrite each other
Atomics.add(counter, 0, 1); // one step no other thread can cut into
Measured in Chromium 147, on a cross-origin isolated page: counter[0]++ gave 1,128,847, 1,372,249 and 1,439,138 in three tries, not 4,000,000. That is called a data race. Atomics.add gave 4,000,000 every time.
Atomics.load,Atomics.store,Atomics.add,Atomics.sub,Atomics.compareExchange: whole reads and writes that no other thread can cut into.Atomics.wait(arr, i, value)puts a thread to sleep untilAtomics.notify(arr, i)wakes it. On the main thread it is forbidden, so the page cannot freeze: Chromium 147 throwsTypeError: Atomics.wait cannot be called in this context. On the main thread, useAtomics.waitAsync, which returns a Promise.
Why SharedArrayBuffer needs cross-origin isolation
In 2018, the Spectre attack showed that code with a very precise timer could guess the contents of other memory in the same process. A SharedArrayBuffer can be used to build such a timer, so browsers only offer it to pages that are cross-origin isolated: pages that refuse to load alongside documents from other origins. That takes two headers on the document:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
COOP: same-origincuts the link with windows from other origins (popups,window.opener).COEP: require-corponly allows resources from other origins (CDN images, scripts, iframes) that send aCross-Origin-Resource-Policyheader or pass CORS. The rest are blocked.COEP: credentiallessloads those resources without cookies instead; it works in Chromium 147 and Firefox 146, but WebKit 26.4 rejects it (crossOriginIsolatedstaysfalse).- Check in the console:
crossOriginIsolatedmust betrue.
Without those headers, in Chromium 147, WebKit 26.4 and Firefox 146: crossOriginIsolated is false and typeof SharedArrayBuffer is "undefined". Surprisingly, new WebAssembly.Memory({ initial: 1, maximum: 1, shared: true }) can still be created, and its buffer really is a SharedArrayBuffer. What fails is sending it to a worker:
Chromium 147: DataCloneError: Failed to execute 'postMessage' on 'Worker': SharedArrayBuffer transfer requires self.crossOriginIsolated.
WebKit 26.4: DataCloneError: The object can not be cloned.
Firefox 146: DataCloneError: Worker.postMessage: The WebAssembly.Memory object cannot be serialized. The Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy HTTP headers can be used to enable this.
The JS Playground on BelajarWeb.dev does not send those headers, so the Lab's code uses transfers, and shows this error as it is when it tries shared memory.
Wasm threads: shared memory and atomic instructions
Wasm has no instruction that creates a thread. "Wasm threads" means: memory marked shared, atomic instructions (i32.atomic.rmw.add, memory.atomic.wait32, memory.atomic.notify), and one instance in each Web Worker, all using the same memory.
;; add-one.wat: wat2wasm --enable-threads add-one.wat -> 64 bytes
(module
(memory (import "env" "memory") 60 60 shared) ;; shared memory must have a maximum
(func (export "addOne") (param $address i32) (result i32)
local.get $address
i32.const 1
i32.atomic.rmw.add)) ;; add 1 atomically, return the old value
- JavaScript creates the memory,
new WebAssembly.Memory({ initial: 60, maximum: 60, shared: true }), then sends it to every worker, where every instance uses it as itsenv.memoryimport. - wat2wasm 1.0.42 refuses without
--enable-threads(error: opcode not allowed: i32.atomic.rmw.add), and(memory 1 shared)without a maximum is refused witherror: shared memories must have max sizes.
Emscripten builds all of that from ordinary C with pthread:
emcc -O3 -pthread -sPTHREAD_POOL_SIZE=8 -sINITIAL_MEMORY=33554432 blur-thread.c -o blur-thread.js
blur-thread.c splits the σ 2 blur across N threads with pthread_create and pthread_join: the horizontal blur on every thread, wait for them all, then the vertical blur. Emscripten 6.0.12 produces blur-thread.js (21,370 bytes) and blur-thread.wasm (31,048 bytes). PTHREAD_POOL_SIZE=8 gets 8 workers ready before main() runs. On a page with COOP and COEP:
| Threads | Chromium 147 | WebKit 26.4 |
|---|---|---|
| 1 | 43.4 ms | 44.2 ms |
| 2 | 22.2 ms | 21.8 ms |
| 4 | 14.3 ms | 11.2 ms |
| 8 | 11.2 ms | 9.9 ms |
Its result's checksum matches the JavaScript blur. The same page without the headers never reaches main(): Chromium stops with the same DataCloneError as above. For Rust, the wasm-bindgen-rayon crate (1.3.0) gives a Rayon thread pool on top of Web Workers, but still needs nightly Rust with -Z build-std and +atomics,+bulk-memory.
⚠️ The missing SharedArrayBuffer and the counts that come out wrong
- Forgetting the COOP and COEP headers.
SharedArrayBufferbecomesundefined, and a-pthreadbuild fails with aDataCloneError. CheckcrossOriginIsolated. require-corpblocking images from another CDN. Resources from other origins must sendCross-Origin-Resource-Policyor CORS, or usecredentialless(not in Safari yet).- Writing shared memory without Atomics. 4 × 1,000,000 additions end up as about 1.1 to 1.4 million.
Atomics.waiton the main thread. ATypeError. UseAtomics.waitAsync, or wait in a worker.- Workers for small jobs. A 1.2 ms grayscale does not get faster split in 4. Split jobs that take tens of milliseconds.
TL;DR: Threading in the browser = Web Workers. Data can be moved (a transferable ArrayBuffer, postMessage(data, [buffer])) or shared through a SharedArrayBuffer, with Atomics to prevent data races (counter[0]++ from 4 workers: about 1.4 million, Atomics.add: exactly 4 million). A σ 2 blur split across 4 workers, with 6 extra rows per side: 50 ms becomes 15 ms in Chromium 147 (3.3×), not 4×. SharedArrayBuffer only exists on a cross-origin isolated page: Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp (or credentialless, not in Safari yet); check crossOriginIsolated. Without that, shared Wasm memory can still be created, but its postMessage fails with a DataCloneError. Wasm threads = shared memory + atomic instructions + one instance per worker; Emscripten -pthread builds it from C (the blur goes from 43 ms to 11 ms with 8 threads), Rust through wasm-bindgen-rayon on nightly. Atomics.wait is forbidden on the main thread.
⚡ Threads in the browser are Web Workers
Write:
const result = x.memory.buffer.slice(base + d.skip * d.W * 4, base + (d.skip + d.rows) * d.W * 4);
postMessage(result, [result]); // transfer: moved, not copied
Meaning: A Worker runs its own JavaScript file on another thread and cannot touch the DOM. An ArrayBuffer in the transfer list moves to the other thread in almost no time, and on the sender's side its length becomes 0.
⚡ 4 workers, not 4 times faster
Guess first: a blur that takes 50 ms in one worker is split across 4 workers. Does it take 12.5 ms, about 15 ms, or still 50 ms?
About 15 ms (15.1 ms in Chromium 147). The rest is the cost of copying the strips and the extra rows, sending messages and assembling the result.
Meaning: Split jobs that take tens of milliseconds. A 1.2 ms grayscale does not get faster split in 4.
⚡ Shared memory needs Atomics
Write:
const counter = new Int32Array(new SharedArrayBuffer(4));
counter[0]++; // read, add, write: they can overwrite each other
Atomics.add(counter, 0, 1); // one step no other thread can cut into
Meaning: With 4 workers adding 1,000,000 times each, counter[0]++ only reaches about 1.1 to 1.4 million. That is a data race. Atomics.add gives exactly 4,000,000 every time.
⚡ SharedArrayBuffer needs isolation
Write:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp
Meaning: Since Spectre, SharedArrayBuffer only exists on a cross-origin isolated page. Check crossOriginIsolated. Wasm threads = shared memory + atomic instructions + one instance in each Web Worker, all using the same memory.