Expand description
Constructors§
Methods§
Source§lock(): MutexGuard<MutexData<T>>
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>>
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');
A mutual exclusion lock (mutex) for synchronizing access to shared data.