Rust-like Mutex and Semaphore for TypeScript
Node Package 📦
- 100% TypeScript and ESM
- No external dependencies
- Similar to Rust
- Can hold data
- Unit-tested
- Memory-safe
import{Mutex}from"@hazae41/mutex"constmutex=newMutex(123)/** * You can queue a callback */asyncfunctionrunOrWait(){awaitmutex.runOrWait((x)=>/* do (async) stuff with x */)}/** * You can throw if the mutex is already locked */asyncfunctionrunOrThrow(){awaitmutex.runOrThrow((x)=>/* do stuff with x */)}/** * You can return something from the callback */asyncfunctionrunOrWait2(){consty=awaitmutex.runOrWait((x)=>x*2)}/** * You can use async code */asyncfunctionrunOrWait3(){consty=awaitmutex.runOrWait(async(x)=>awaitf(x))}/** * You can acquire and release when you want */asyncfunctiongetOrWait(){constx=awaitmutex.getOrWait()consty=x.get()*2x.release()}/** * You can acquire and release with `using` */asyncfunctiongetOrWait2(){ usingx=awaitmutex.getOrWait()consty=x.get()*2}
Same functions as Mutex but you can specify a capacity
constsemaphore=newSemaphore(123,3)consta=awaitsemaphore.getOrThrow()constb=awaitsemaphore.getOrThrow()constc=awaitsemaphore.getOrThrow()constd=awaitsemaphore.getOrThrow()// will throw
You can see it likeMutex<T> = Semaphore<T, 1>