The most simple mutex/semaphore implementation
npm install superlock!Last version


> A mutex/semaphore implementation made easy to use.
superlock aims to be:
- Simple: Designed for usage with async and await
- Powerful: Mutex & Semaphore patterns supported
- Secure: Auto lock release toa void dead locks
- Lightweight: No dependencies, just ~50 LOC
- Well-tested: 100% code coverage
``bash`
$ npm install superlock --save
The lock is a mutex by default:
`js
const { setTimeout } = require('timers/promises')
const { withLock } = require('superlock')
const lock = withLock()
const executions = await Promise.all(
[...Array(10).keys()].map(index =>
lock(async () => {
await setTimeout(Math.random() * 100)
return index
})
)
)
console.log(executions)
`
Just call withLock(n) being n the maximum of concurrency desired for the lock.
It returns a function that can be used to wrap any code you want to execute with concurrency control:
`js
const { withLock } = require('superlock')
const lock = withLock()
await lock(() => {
/ your code execution /
})
`
The lock will be automatically released after your code execution is done even if an error occurred, avoiding deadlock situations.
#### concurrency
Type: number1
Default:
It sets the maximum of concurrency allowed for the lock.
Type: boolean
It returns false` if there is at least one free concurrency slots in the lock.
superlock © Kiko Beats, released under the MIT License.
Authored and maintained by Kiko Beats with help from contributors.
> kikobeats.com · GitHub Kiko Beats · X @Kikobeats