A mutual exclusion (mutex) class that ensures only one asynchronous operation can execute at a time, providing thread-safe execution of critical sections.

const mutex = new Mutex();

// Only one of these will execute at a time
mutex.lock(async () => {
// Critical section code here
return someAsyncOperation();
});

Constructors

Methods

Constructors

Methods

  • Acquires the mutex lock and executes the provided function. The function will not execute until all previously queued operations complete.

    Type Parameters

    • T

      The return type of the function

    Parameters

    • fn: (() => T | Promise<T>)

      The function to execute while holding the mutex lock. Can be synchronous or asynchronous.

        • (): T | Promise<T>
        • Returns T | Promise<T>

    Returns Promise<T>

    A promise that resolves with the result of the function execution

    const result = await mutex.lock(async () => {
    // This code is guaranteed to run exclusively
    return await someAsyncOperation();
    });