1.0.0 โข Published 9 months ago
@direct-dev-ru/rwmutex-ts v1.0.0
rwmutex-ts
๐งต Reader-writer mutex for TypeScript / ESM with timeout support and lock priority
โจ Features
- โ Asynchronous read-write mutex implementation
- โฑ๏ธ Supports timeout for lock acquisition
- โ๏ธ Prioritizes writers over readers to avoid starvation
- ๐งช Tested with Vitest
- ๐ฆ ESM-native and typed (
.d.ts)
๐ฆ Installation
npm install rwmutex-ts๐ง Usage
import { RWMutex } from 'rwmutex-ts';
const mutex = new RWMutex();
// Reader section
await mutex.withReadLock(async () => {
// Shared resource access
});
// Writer section
await mutex.withWriteLock(async () => {
// Exclusive access
});โฑ๏ธ Lock Timeout Example
You can pass a timeout (in milliseconds) to abort if the lock can't be acquired:
try {
await mutex.withWriteLock(async () => {
// critical section
}, 200); // try for max 200ms
} catch (err) {
console.error('Write lock timeout:', err);
}๐งช Test
npm run test๐ API
withReadLock(fn: () => Promise<T>, timeoutMs?: number): Promise<T>
Executes fn under a read lock. Fails if the lock cannot be acquired within the timeout.
withWriteLock(fn: () => Promise<T>, timeoutMs?: number): Promise<T>
Executes fn under a write lock. Timeout behaves the same.
๐ License
MIT ยฉ 2025 Your Name
๐ Example Projects
- ๐ Locking shared config access in SSR apps
- ๐ Concurrent file readers
- ๐งต Concurrency control in worker pools
PRs and issues welcome!
1.0.0
9 months ago