Compile the shared-compatible teaching binary once. A WebAssembly.Modulecan be sent through postMessage, and each worker instantiates it with the shared memory import. An instance is not the thing to send. Its host bindings and runtime state belong to its environment. Neither the module nor the shared memory belongs in a transfer list; this is not detaching an ordinary buffer from its sender. The Module API reference describes reuse across workers.
const sharedModule = await WebAssembly.compile(sharedSumWasmBytes);
worker.postMessage({
id: "range-1",
generation: 1,
module: sharedModule,
memory,
pointer: 68,
length: 2,
});
The dispatch fragment assumes the compiled-byte array supplied by the playground and an existing worker. Its range starts at the second order: 64 + 1 * 4 = 68. The following worker handles one bounded range. The caller validates dataset values and the maximum total before dispatch, just as in Part 2. The worker validates its byte range again before passing scalar arguments to Wasm.
self.onmessage = async ({ data }) => {
try {
const { module, memory, pointer, length } = data;
const byteLength = memory.buffer.byteLength;
if (!Number.isInteger(pointer) || pointer < 64 || pointer % 4 !== 0 ||
!Number.isInteger(length) || length < 0 ||
pointer > byteLength || length > (byteLength - pointer) / 4) {
throw new RangeError("Invalid range");
}
const control = new Int32Array(memory.buffer, 0, 2);
const instance = await WebAssembly.instantiate(module, { env: { memory } });
while (Atomics.load(control, 0) === 0) {
Atomics.wait(control, 0, 0);
}
if (Atomics.load(control, 0) !== 1) throw new Error("Run was not published");
const partial = instance.exports.sum(pointer, length);
const previousCompleted = instance.exports.markDone();
self.postMessage({ id: data.id, generation: data.generation, ok: true, partial, previousCompleted });
} catch (error) {
self.postMessage({
id: data.id,
generation: data.generation,
ok: false,
error: error instanceof Error ? error.message : String(error),
});
}
};
The wait belongs in the worker. The browser main thread must remain able to process input, messages, and failure timers. Check the condition in a loop: waking is an opportunity to recheck state, not ownership of a ready job. In this one-shot example, publication may happen before a worker starts waiting; the load and value check keep it from sleeping for a notification that already happened.
The shared teaching module adds the following function beside sum. It atomically adds one at byte offset four, which is control-word index one in JavaScript, and returns the previous value. This makes the interoperability concrete: Wasm performs the atomic read-modify-write, while the coordinator observes the same location with Atomics.load(control, 1).
(func (export "markDone") (result i32)
(i32.atomic.rmw.add (i32.const 4) (i32.const 1)))
The atomic completion count is useful progress metadata. It does not replace collecting one result per expected request ID. A production coordinator rejects duplicate or stale results, times out stalled jobs, and cleans up all workers on failure. Use a new generation and fresh memory for a restarted run so old results cannot silently enter the new total.