1.0.0 โ€ข Published 9 months ago

@direct-dev-ru/rwmutex-ts v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

rwmutex-ts

๐Ÿงต Reader-writer mutex for TypeScript / ESM with timeout support and lock priority

npm license test

โœจ 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!