mutex-async
v1.0.2
Published
A javascript mutex designed for async/await
Maintainers
Readme
Mutex Async
A basic javascript library that provides an asynchronous mutex. Designed for use with for async/await. It supports a variable number of locks at a time.
Installation
npm install mutex-asyncUsage
const mutexAsync = require('mutex-async');
const mutex = new mutexAsync.Mutex();
async function criticalSection() {
let unlock = await mutex.lock();
try {
// Critical section code here
} catch(err) {
}
await unlock();
}
// or
async function criticalSection() {
await mutex.run(async () => {
// Critical section code here
});
}Multiple simultaneous locks
const mutexAsync = require('mutex-async');
const mutex = new mutexAsync.Mutex({
maxLocks: 10
});
async function criticalSection() {
let unlock = await mutex.lock();
try {
await new Promise(resolve => setTimeout(resolve, 1000));
} catch(err) {}
await unlock();
}
// will only take 2 seconds
let promises = [];
for(let i = 0; i < 20; i++) {
promises.push(criticalSection());
}
await Promise.all(promises);Functions
- mutex.lock() - returns a promise that resolves to a function that will unlock the mutex when the mutex is available
- mutex.run(fn) - runs the function fn when the mutex is available, returns a promise that resolves to the return value of fn
- mutex.isLocked() - returns true if the mutex is currently locked and the next lock will wait, false otherwise
- mutex.getLockCount() - returns the number of locks currently held
- mutex.getWaitCount() - returns the number of locks waiting to be resolved.
- mutex.unlock() - unlocks the mutex, if there are any waiting locks, the next one will be resolved immediately. use the unlock function returned by lock() instead for better protection against double unlocks.
Options
These options are configured by passing in an object with them into the constructor. Also they can also be changed at any time by assigning a new value to the property of the same name on the mutex instance.
- maxLocks - the maximum number of locks that can be held at the same time, default is 1.
- warnOnOverlap - if true, will log a warning whenever a lock needs to wait for another to complete. default is false.
License
MIT License
