Ferrous API Reference

All Types / Ferrous.Concurrency

class Mutex<T>

public sealed class Mutex<T>

A data-owning mutual exclusion primitive inspired by Rust's std::sync::Mutex<T>. The protected value can only be accessed while holding a stack-allocated MutexGuard<T>.

Type Parameters
T
The type of the protected value.

Constructors

public Mutex(T initialValue)

Initializes a new Mutex<T> owning initialValue.

Parameters
initialValue
The initial protected value.

Methods

public MutexGuard<T> Lock()
[MustUse]

Acquires the mutex and returns a stack-allocated MutexGuard<T> providing exclusive access to the protected value.

Returns: A MutexGuard<T> that releases the lock when disposed.

public bool TryLock(out MutexGuard<T> guard)
[MustUse]

Attempts to acquire the mutex without blocking.

Parameters
guard
When this method returns true, contains the acquired MutexGuard<T>; otherwise, the default (unacquired) guard.

Returns: true if the lock was acquired; otherwise, false.

public void WithLock(Action<T> action)

Acquires the lock, invokes action with the protected value, and releases the lock.

Parameters
action
The callback to execute while holding the lock.
public TResult WithLock<TResult>(Func<T, TResult> func)

Acquires the lock, invokes func with the protected value, releases the lock, and returns the result.

Type Parameters
TResult
The return type of func.
Parameters
func
The callback to execute while holding the lock.

Returns: The value returned by func.