Skip to content

Mutex

Spice
import "std/os/mutex";

Mutex struct

Mutex for reserving a resource for exclusive access between threads.

Backed by a POSIX pthread_mutex_t. Calls to acquire block until the mutex is available; release wakes up another waiting thread, if any. A Mutex owns the underlying pthread handle and is not safe to share by shallow copy — use a reference (Mutex&) when passing across functions.

Constructors

ctor

Spice
public p Mutex.ctor()

Initialize a fresh, unlocked mutex.

ctor

Spice
public p Mutex.ctor(const Mutex& _other)

Copy-construct a fresh, unlocked mutex. The original mutex is not aliased, since pthread_mutex_t handles cannot be safely shared via shallow copy.

Parameters

Name Type Description
_other const Mutex&

dtor

Spice
public p Mutex.dtor()

Destroy the underlying pthread mutex and release its storage.

Methods

acquire

Spice
public p Mutex.acquire()

Block until the mutex is acquired by the calling thread.

release

Spice
public p Mutex.release()

Release the mutex, allowing another waiting thread to acquire it.

tryAcquire

Spice
public f<bool> Mutex.tryAcquire()

Try to acquire the mutex without blocking.

Returns: bool — true if the mutex was acquired, false if another thread holds it

LockGuard struct

LockGuard is a RAII wrapper for Mutex: acquires on construction and releases on destruction, ensuring the mutex is freed even when the protected scope exits via an early return or a panic.

Constructors

ctor

Spice
public p LockGuard.ctor(Mutex& mutex)

Acquire the mutex

Parameters

Name Type Description
mutex Mutex&

dtor

Spice
public p LockGuard.dtor()

Release the mutex

Operators

operator=

Spice
public p operator=(Mutex& this, const Mutex& _other)

Assignment for Mutex. Spice falls back to the copy constructor for plain struct assignment, which would unconditionally allocate a new pthread_mutex_t and leak the receiver's existing handle. A Mutex owns a unique resource, so the only meaningful "copy" is a fresh independent mutex — and the receiver already is one. We therefore keep the receiver's handle in place and only lazily initialize if it was previously destroyed or never set up.

Parameters

Name Type Description
_other const Mutex&