Class Mutex<T>

Source
Expand description

A mutual exclusion lock (mutex) for synchronizing access to shared data.

import { Mutex } from '../src/index.js';

class TokenStore {
private token?: string;
private readonly mutex = new Mutex(void 0);

public async getToken(): Promise<string> {
console.log('Requesting token...');
await using lock = this.mutex.lock();
await lock; // Wait for the lock to be acquired
if (this.token) {
console.log('Reusing existing token:', this.token);
return this.token;
}
const token = await new Promise<string>((resolve) => {
queueMicrotask(() => {
resolve('token-123');
});
});
console.log('Fetched new token', token);
this.token = token; // Update the shared token
return token;
}
}

const store = new TokenStore();

store.getToken();
store.getToken();
store.getToken();

Constructors§

Source§

new Mutex<T>(data: T): Mutex<T>

Methods§

Source§

lock(): MutexGuard<MutexData<T>>

Acquires the mutex, returning a guard that will release the lock when disposed.

import { Mutex } from '../src/index.js';

const mutex = new Mutex(void 0);

async function process(name: string): Promise<void> {
await using lock = mutex.lock();
console.log(name, 'Acquiring lock...');
await lock;
console.log(name, 'Acquired lock');
console.log(name, 'Releasing lock...');
}

process('A');
process('B');
Source§

tryLock(): MutexGuard<undefined | MutexData<T>>

Attempts to acquire the mutex without waiting. If the lock is not available, returns a guard with undefined data.

import { Mutex } from '../src/index.js';

const mutex = new Mutex(void 0);

async function process(name: string): Promise<void> {
await using lock = mutex.tryLock();
console.log(name, 'Acquiring lock...');
if (await lock) {
console.log(name, 'Acquired lock');
} else {
console.log(name, 'Could not acquire lock');
return;
}
console.log(name, 'Releasing lock...');
}

process('A');
process('B');