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
- Uses Result from
@hazae41/result
Usage
Mutex
import { Mutex } from "@hazae41/mutex"
const mutex = new Mutex(123)
async function lockOrWait() {
await mutex.lock(async (x) => )
}
async function lockOrWaitAndLog() {
const x = await mutex.lock(async (x) => x)
console.log(x)
}
async function lockOrThrow() {
await mutex.lockOrThrow(async (x) => )
}
async function tryLock() {
const result = mutex.tryLock(async (x) => )
if (result.isErr())
throw result.getErr()
await result.get()
}
async function wait() {
await mutex.wait()
}
async function acquire() {
const lock = await mutex.acquire()
console.log(lock.get())
lock.release()
}
async function acquireAndUse() {
using lock = await mutex.acquire()
console.log(lock.get())
}
Semaphore
Same functions as Mutex but you can specify a capacity