Socket
Book a DemoInstallSign in
Socket

@hazae41/mutex

Package Overview
Dependencies
Maintainers
1
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@hazae41/mutex

Rust-like Mutex for TypeScript

latest
Source
npmnpm
Version
2.2.2
Version published
Maintainers
1
Created
Source

Mutex

Rust-like Mutex and Semaphore for TypeScript

npm i @hazae41/mutex

Node Package 📦

Features

Current features

  • 100% TypeScript and ESM
  • No external dependencies
  • Similar to Rust
  • Can hold data
  • Unit-tested
  • Memory-safe

Usage

Mutex

import { Mutex } from "@hazae41/mutex"

const mutex = new Mutex(123)

/**
 * You can queue a callback 
 */
async function runOrWait() {
  await mutex.runOrWait((x) => /* do (async) stuff with x */)
}

/**
 * You can throw if the mutex is already locked
 */
async function runOrThrow() {
  await mutex.runOrThrow((x) => /* do stuff with x */)
}

/**
 * You can return something from the callback
 */
async function runOrWait2() {
  const y = await mutex.runOrWait((x) => x * 2)
}

/**
 * You can use async code
 */
async function runOrWait3() {
  const y = await mutex.runOrWait(async (x) => await f(x))
}

/**
 * You can acquire and release when you want
 */
async function getOrWait() {
  const x = await mutex.getOrWait()
  const y = x.get() * 2
  x.release()
}

/**
 * You can acquire and release with `using`
 */
async function getOrWait2() {
  using x = await mutex.getOrWait()
  const y = x.get() * 2
}

Semaphore

Same functions as Mutex but you can specify a capacity

const semaphore = new Semaphore(123, 3)

const a = await semaphore.getOrThrow()
const b = await semaphore.getOrThrow()
const c = await semaphore.getOrThrow()
const d = await semaphore.getOrThrow() // will throw

You can see it like Mutex<T> = Semaphore<T, 1>

Keywords

mutex

FAQs

Package last updated on 18 Jun 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts