Mutex<T>
Struct · namespace System · Since 0.04
struct Mutex<T>A value that several threads share, guarded by a lock.
thread void Count(Mutex<int> counter, int times){ for (var i = 0; i < times; i += 1) counter.Update(n => n + 1); // or: using (var guard = counter.Lock()) guard.Set(guard.Get() + 1);}
var counter = Mutex<int>.Create(0);A Mutex<T> is a handle: copies share the same value and lock, and it can be passed to thread functions. The
value only goes in and out as a copy that shares no reference count with anything else (strings are copied into
new blocks), so T must be a type that can be copied between threads: numbers, bool, char, enums, strings,
ReadOnlySlice<T> of them, SharedPtr<T> of thread-safe values, and Optional<T>/Error<T>/structs made of
them - not arrays or containers. While a guard (Mutex<T>.Lock) is held, its Get/Set are safe from every
thread; Mutex<T>.Get and Mutex<T>.Set lock just for the one call.
Static methods
Section titled “Static methods”| Name | Description |
|---|---|
Create |
A new mutex that holds a copy of value. |
Create
Section titled “Create”static Mutex<T> Create(T value)A new mutex that holds a copy of value.
Methods
Section titled “Methods”| Name | Description |
|---|---|
Lock |
Waits for the lock and returns a guard that holds it; the guard’s Dispose (e.g. through using) releases it. |
Get |
A copy of the value (locks for the duration of the call). |
Update |
Replaces the value with change(value), under the lock: counter.Update(n => n + 1). |
Set |
Replaces the value (locks for the duration of the call). |
MutexGuard<T> Lock()Waits for the lock and returns a guard that holds it; the guard’s Dispose (e.g. through using) releases it.
T Get()A copy of the value (locks for the duration of the call).
Update
Section titled “Update”void Update(Func<T, T> change)Replaces the value with change(value), under the lock: counter.Update(n => n + 1).
void Set(T value)Replaces the value (locks for the duration of the call).