happy-rusty
    Preparing search index...

    Interface Mutex<T>

    An async mutual exclusion primitive for protecting shared data.

    This mutex provides exclusive access to the contained value, ensuring that only one async operation can access it at a time. This is useful for preventing race conditions in async code.

    Unlike Rust's Mutex which is for multi-threading, this JavaScript version serializes async operations in the single-threaded event loop.

    1.6.0

    const mutex = Mutex({ balance: 100 });

    // Safe concurrent updates
    await Promise.all([
    mutex.withLock(async (account) => {
    account.balance -= 50;
    }),
    mutex.withLock(async (account) => {
    account.balance += 30;
    }),
    ]);
    interface Mutex<T> {
        "[toStringTag]": "Mutex";
        get(): Promise<Awaited<T>>;
        isLocked(): boolean;
        lock(): Promise<MutexGuard<T>>;
        replace(value: T): Promise<Awaited<T>>;
        set(value: T): Promise<void>;
        toString(): string;
        tryLock(): Option<MutexGuard<T>>;
        withLock<U>(fn: (value: T) => U | PromiseLike<U>): Promise<Awaited<U>>;
    }

    Type Parameters

    • T

      The type of the protected value.

    Index

    Properties

    "[toStringTag]": "Mutex"

    The well-known symbol Symbol.toStringTag used by Object.prototype.toString(). Returns 'Mutex' so that Object.prototype.toString.call(mutex) produces '[object Mutex]'.

    Methods

    • Acquires the lock and returns a copy of the protected value.

      This is a convenience method equivalent to withLock(v => v).

      Returns Promise<Awaited<T>>

      A promise that resolves to a copy of the value.

      const mutex = Mutex(42);
      const value = await mutex.get();
      console.log(value); // 42
    • Returns true if the mutex is currently locked.

      Note: This is a snapshot and may change immediately after the call.

      Returns boolean

      console.log(mutex.isLocked()); // false
      const guard = await mutex.lock();
      console.log(mutex.isLocked()); // true
      guard.unlock();
      console.log(mutex.isLocked()); // false
    • Acquires the lock and returns a guard for manual control.

      Use this when you need more control over when to release the lock. Important: Always release the lock in a finally block to prevent deadlocks.

      Returns Promise<MutexGuard<T>>

      A promise that resolves to a guard providing access to the value.

      const guard = await mutex.lock();
      try {
      // Long-running operation with the protected value
      await processData(guard.value);
      guard.value = transformedData;
      } finally {
      guard.unlock();
      }
    • Acquires the lock, sets a new value, and returns the old value.

      This is a convenience method equivalent to:

      withLock(old => { value = newValue; return old; })
      

      Parameters

      • value: T

        The new value to set.

      Returns Promise<Awaited<T>>

      A promise that resolves to the old value.

      const mutex = Mutex(42);
      const old = await mutex.replace(100);
      console.log(old); // 42
      console.log(await mutex.get()); // 100
    • Acquires the lock and sets a new value.

      This is a convenience method equivalent to withLock(() => { value = newValue; }).

      Parameters

      • value: T

        The new value to set.

      Returns Promise<void>

      A promise that resolves when the value has been set.

      const mutex = Mutex(42);
      await mutex.set(100);
      console.log(await mutex.get()); // 100
    • Custom toString implementation.

      Returns string

      const mutex = Mutex(42);
      console.log(mutex.toString()); // 'Mutex(<unlocked>)'

      const guard = await mutex.lock();
      console.log(mutex.toString()); // 'Mutex(<locked>)'
    • Attempts to acquire the lock without waiting.

      Returns immediately with Some(guard) if the lock is available, or None if it's currently held by another operation.

      Returns Option<MutexGuard<T>>

      Some(guard) if acquired, None if locked.

      const maybeGuard = mutex.tryLock();
      if (maybeGuard.isSome()) {
      const guard = maybeGuard.unwrap();
      try {
      // Use the value
      } finally {
      guard.unlock();
      }
      } else {
      console.log('Mutex is busy');
      }
    • Acquires the lock and executes the callback with the protected value.

      This is the recommended way to use the mutex as it automatically releases the lock when the callback completes (or throws).

      Type Parameters

      • U

        The return type of the callback.

      Parameters

      • fn: (value: T) => U | PromiseLike<U>

        The callback that receives the protected value.

      Returns Promise<Awaited<U>>

      A promise that resolves to the callback's return value.

      const mutex = Mutex<number[]>([]);

      await mutex.withLock(async (arr) => {
      arr.push(await fetchItem());
      });