Qu

mutex

Builtin index · Concurrency

result = mutex(initial)

Input: initial · Output: result

What it is

Creates a shared mutable cell holding initial (any value, of any type — the mutex has no fixed element type).

Overloads

One call shape — this function is not overloaded.

CodeInputOutputDescription
result = mutex(initial)
initial Mutexnot documented yet
result Mutex
Returns a Mutex handle (type(m) == "mutex"); cloning that handle (assigning it, capturing it into a worker's snapshot) shares the same underlying cell rather than copying the value inside it.

Examples

From the documentation, and run by the build -- the output and the figure below are what the engine actually produced. Simplest first.

counter = mutex(0)
parallel for i in 1 to 100
    mutex_add(counter, 1)
end parallel
print("total {mutex_get(counter)}")
output
total 100

from specialized

counter = mutex(0)
parallel for i in 1 to 100
    mutex_add(counter, 1)              # atomic; 100 in, 100 out, no lost updates

end parallel
total = mutex_get(counter)
print(total)                           # 100

output
100

from concurrency

running_max(current) := max(current, 7)

m = mutex(0)
mutex_set(m, 3)                        # overwrite -- no read involved

mutex_update(m, "running_max")         # atomic read-modify-write via a user fn

print(mutex_get(m))                    # 7

output
7

from concurrency

How it works

mutex(initial) — genuinely SHARED mutable state, the deliberate opt-in exception to spawn/parallel for's default share-nothing design: pass the same mutex variable into multiple workers (it survives an env-snapshot clone because cloning Value::Mutex clones the Arc, not the data — every clone still points at the same cell) when you genuinely need a shared counter, accumulator, or cache.

From the note above this builtin in the interpreter, where the reasoning was written down as it was built.