Async Mutex With FIFO Queue
Implement an async mutex with FIFO fairness for exclusive access to shared resources without priority inversion.
Code
export function asyncMutex(){let locked=false;const queue=[];async function acquire(){if(!locked){locked=true;return;}return new Promise(resolve=>queue.push(resolve));}function release(){if(queue.length>0){const next=queue.shift();next();}else locked=false;}function withLock(fn){return async(...args)=>{await acquire();try{return await fn(...args);}finally{release();}};}return{acquire,release,withLock,isLocked:()=>locked};}The mechanics
Async Mutex With FIFO Queue keeps everything in the functions asyncMutex, acquire, release and withLock.
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 acquire, release, withLock.
Applying it
The primary signature is export function asyncMutex()
The surface worth importing is asyncMutex; the helpers around it are private to the snippet.
The call returns acquire, release, withLock — destructure what you need at the call site.
Interactive Tools for This Topic
FAQ
- Does `asyncMutex` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Does this require external packages?
- No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `asyncMutex`, `acquire`, `release` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.