Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

superlock

Kikobeats5.3kMIT1.2.2TypeScript support: included

The most simple mutex/semaphore implementation

async, await, concurrency, critical, lock, mutex, section, semaphore

readme

Last version Coverage Status NPM Status

A mutex/semaphore implementation made easy to use.

Why

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

Install

$ npm install superlock --save

Usage

as mutex

The lock is a mutex by default:

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)

as semaphore

Just call withLock(n) being n the maximum of concurrency desired for the lock.

API

withLock([concurrency=1])

It returns a function that can be used to wrap any code you want to execute with concurrency control:

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: number
Default: 1

It sets the maximum of concurrency allowed for the lock.

.isLocked()

Type: boolean

It returns false if there is at least one free concurrency slots in the lock.

License

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

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

1.2.2 (2024-11-19)

1.2.1 (2024-10-14)

1.2.0 (2024-08-30)

1.1.5 (2024-08-19)

1.1.4 (2024-08-19)

1.1.3 (2024-05-09)

1.1.2 (2024-05-02)

1.1.1 (2024-04-26)

Bug Fixes

1.1.0 (2024-04-16)

Features

1.0.8 (2024-04-14)

1.0.7 (2024-02-08)

1.0.6 (2024-01-07)

1.0.5 (2023-10-24)

1.0.4 (2023-09-05)

1.0.3 (2023-08-10)

1.0.2 (2023-02-06)

1.0.1 (2022-11-21)

1.0.0 (2022-08-04)

0.0.1 (2022-08-04)