Async Read Write Lock

Implement a read-write lock allowing concurrent readers or a single writer with upgrade support for shared state.

JavascriptResilience

Code

javascriptsnippet
1 line
export function rwLock(){let readers=0,writing=false;const readQueue=[],writeQueue=[];async function readLock(){if(writing||writeQueue.length>0)return new Promise(r=>readQueue.push(r));readers++;}function readUnlock(){readers--;if(readers===0&&writeQueue.length>0)writeQueue.shift()();}async function writeLock(){if(readers>0||writing)return new Promise(r=>writeQueue.push(r));writing=true;}function writeUnlock(){writing=false;if(readQueue.length>0)while(readQueue.length>0)readQueue.shift()();else if(writeQueue.length>0)writeQueue.shift()();}return{readLock,readUnlock,writeLock,writeUnlock};}

Inside the snippet

Count the functions rwLock, readLock, readUnlock and writeLock as the entire surface area of Async Read Write Lock.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The result comes back as an object carrying readLock, readUnlock, writeLock.

Points of care

  • The guard writing||writeQueue.length>0 short-circuits the flow with an early return when its condition holds.

Using it

Entry signature: export function rwLock()

rwLock is what another module would consume; nothing else here is load-bearing for callers.

The call returns readLock, readUnlock, writeLock — destructure what you need at the call site.

Interactive Tools for This Topic

FAQ

Does `rwLock` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `rwLock`, `readLock`, `readUnlock` at load time.