Skip to content

Instantly share code, notes, and snippets.

@RioChndr
Created April 2, 2026 08:37
Show Gist options
  • Select an option

  • Save RioChndr/40c62f6912df613400122eb06c5401bd to your computer and use it in GitHub Desktop.

Select an option

Save RioChndr/40c62f6912df613400122eb06c5401bd to your computer and use it in GitHub Desktop.
Shared value, atomic Operation, Free race condition, async mutex minimal PoC
const SharedLock = new SharedArrayBuffer(4); // Create a shared buffer for lock
const ArrayLock = new Int32Array(SharedLock); // Create an Int32Array view for atomic operations
async function acquireLock(): Promise<void> {
while (isLocked()) {
await new Promise(resolve => setTimeout(resolve, 100)); // wait for 100ms before retrying
}
Atomics.store(ArrayLock, 0, 1); // acquire lock
}
function releaseLock(): void {
Atomics.store(ArrayLock, 0, 0); // release lock
}
function isLocked(): boolean {
return Atomics.load(ArrayLock, 0) === 1;
}
async function testLock() {
console.log(`Initial lock status: ${isLocked() ? 'Locked' : 'Unlocked'}`);
const simulateProcess = async (id: number) => {
console.log(`Process ${id} is trying to acquire lock...`);
await acquireLock();
console.log(`Process ${id} has acquired lock.`);
await new Promise(resolve => setTimeout(resolve, 2000)); // Simulate some work
console.log(`Process ${id} is releasing lock...`);
releaseLock();
console.log(`Process ${id} has released lock.`);
}
console.log('Acquiring lock...');
await Promise.all([
simulateProcess(1),
simulateProcess(2),
simulateProcess(3)
])
console.log(`Lock status after acquiring: ${isLocked() ? 'Locked' : 'Unlocked'}`);
console.log('Releasing lock...');
releaseLock();
console.log(`Lock status after releasing: ${isLocked() ? 'Locked' : 'Unlocked'}`);
}
testLock().catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment