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
}
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, returnstrue
and the caller shouldunlock()
the Mutex to release it.