🎓 A1Learner
🔍
0 of 50 lessons completed

WebAssembly Threads and SharedArrayBuffer

WebAssembly threads share one memory across workers. SharedArrayBuffer is the shared memory.

Start a worker

Each worker runs its own thread.

const worker = new Worker("worker.js");
worker.postMessage("start");

Add with Atomics

Atomics adds one to a shared counter. Run this on an isolated page, as the next lesson shows.

const shared = new SharedArrayBuffer(4);
const view = new Int32Array(shared);
Atomics.add(view, 0, 1);
console.log(view[0]);

Example

const B64 = "AGFzbQEAAAABBwFgAn9/AX8DAgEABwcBA2FkZAAACgkBBwAgACABags=";
(async () => {
  const bytes = Uint8Array.from(atob(B64), c => c.charCodeAt(0));
  const { instance } = await WebAssembly.instantiate(bytes, {});
  console.log("2 + 3 =", instance.exports.add(2, 3));
})();

Key points

  • Threads are workers that run code at the same time.
  • Use SharedArrayBuffer to give workers one shared memory.
  • Use Atomics to change shared values safely.
  • One memory with many workers needs care on every write.
  • Threads need the isolation headers from the next lesson.
  • The loader below proves the module loads without threads.
  • Shared memory lets workers run side by side.

In this example, the code decodes the module bytes from B64 and instantiates the module. It calls add with 2 and 3 and logs the sum. No thread runs here.

Note

this lesson runs no threads, it only shows the model.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What do WebAssembly threads share?