Skip to content

Recursive Mutex

Spice
import "std/os/recursive-mutex";

RecursiveMutex struct

Mutex, which can be acquired multiple times by the thread, that already holds it. Every acquire has to be matched by a release, and other threads can only acquire the mutex after it was released as often as it was acquired.

This is useful for code, that takes a lock and may call back into code, that takes the same lock again (e.g. recursive algorithms over shared data structures). A plain Mutex would deadlock in this case.

It is built on top of Mutex: the owning thread and the acquisition depth are tracked alongside it. Like a Mutex, a RecursiveMutex is not safe to share by shallow copy — use a reference or a pointer when passing it across functions.

Constructors

ctor

Spice
public p RecursiveMutex.ctor()

Initialize a fresh, unlocked recursive mutex.

Methods

acquire

Spice
public p RecursiveMutex.acquire()

Block until the mutex is acquired by the calling thread. Returns immediately, if the calling thread already holds it.

tryAcquire

Spice
public f<bool> RecursiveMutex.tryAcquire()

Try to acquire the mutex without blocking. Succeeds immediately, if the calling thread already holds it.

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

release

Spice
public p RecursiveMutex.release()

Release the mutex once. Other threads can acquire it, as soon as it was released as often as it was acquired. Must only be called by the thread, that holds the mutex.

RecursiveLockGuard struct

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

Constructors

ctor

Spice
public p RecursiveLockGuard.ctor(RecursiveMutex& mutex)

Acquire the mutex

Parameters

Name Type Description
mutex RecursiveMutex&

dtor

Spice
public p RecursiveLockGuard.dtor()

Release the mutex