Skip to content

Mutex ​

Mutex<T> protects exclusive access to a value shared between concurrently spawned tasks.

SignatureMutex<T>(value: T): Mutex<T>

mutex.lock(): Promise<MutexGuard<T>> waits for the lock and resolves with a guard. mutex.tryLock(): MutexGuard<T>? never waits: it resolves immediately with the acquired guard, or None if the lock is currently held elsewhere.

guard.value reads and writes the protected value directly, in place, including compound assignment (guard.value += 1). The lock releases automatically once the guard goes out of scope, so there is no explicit unlock call. A MutexGuard<T> (or MutexGuard<T>? from tryLock) must not still be alive across an await, since holding a lock across a suspension point is a common source of deadlock and starvation (E3034).

Mutex<T>'s payload is restricted to the same subset channel<T> accepts: string, Copy scalars, and arrays of Copy elements (E3037 otherwise).

tyrus
import { Mutex, spawn } from "tyrus:task";

async function main(): Promise<void> {
    const counter = Mutex<u32>(0);
    const handle = spawn(async (): Promise<void> => {
        // `guard.value` reads and writes the protected value in place; the
        // lock releases automatically once `guard` goes out of scope.
        const guard = await counter.lock();
        guard.value += 1;
    });
    await handle.join();
}