Mutex is a synchronization primitive which enforces atomic access to a shared region of code known as the “critical section”. It does this by blocking ensuring only one thread is in the critical section at any given point in time by blocking the others. Mutex can be statically initialized and is at most @sizeOf(u64) large. Use lock() or tryLock() to enter the critical section and unlock() to leave it.

Example:

var m = Mutex{};

{
    m.lock();
    defer m.unlock();
    // ... critical section code
}

if (m.tryLock()) {
    defer m.unlock();
    // ... critical section code
}

Fields

impl: Impl = .{ },

Functions

fn lock(self: *Mutex) void

Acquires the mutex, blocking the caller’s thread until it can. It is undefined …

Acquires the mutex, blocking the caller’s thread until it can. It is undefined behavior if the mutex is already held by the caller’s thread. Once acquired, call unlock() on the Mutex to release it.

fn tryLock(self: *Mutex) bool

Tries to acquire the mutex without blocking the caller’s thread. Returns `false…

Tries to acquire the mutex without blocking the caller’s thread. Returns false if the calling thread would have to block to acquire it. Otherwise, returns true and the caller should unlock() the Mutex to release it.

fn unlock(self: *Mutex) void

Releases the mutex which was previously acquired with lock() or tryLock(). …

Releases the mutex which was previously acquired with lock() or tryLock(). It is undefined behavior if the mutex is unlocked from a different thread that it was locked from.