SharedJsonBuffer allows for Mutex-protected shared memory for JSON objects. It is optimized for high-performance state synchronization of large, persistent objects by using Proxies to reserialize only changed bytes rather than the entire tree.
Note: SharedJsonBuffer has an initialization cost. It is best used for frequent incremental updates to large objects, rather than single-use transfers where standard cloning is faster.
import { spawn, move, Mutex, SharedJsonBuffer } from "multithreading";
const sharedState = new Mutex(new SharedJsonBuffer({
score: 0,
players: ["Main Thread"],
level: {
id: 1,
title: "Start",
},
}));
await spawn(move(sharedState), async (sharedState) => {
using guard = await sharedState.lock();
const state = guard.value;
console.log(`Current Score: ${state.score}`);
// Modify the data
state.score += 100;
state.players.push("Worker1");
// End of scope: Lock is automatically released here
}).join();
// Verify on main thread
using guard = await sharedState.lock();
console.log(guard.value); // { score: 100, players: ["Main Thread", "Worker1"], ... }