tur/mutex
stdlib/mutex.tur
POSIX mutex (pthread_mutex_t) wrapped as ptr<void>.
Since: Phase T19-C
defopaque
linear
Mutex
(Mutex)
defn
mutex-new
(mutex-new :)
allocate and initialise a new POSIX mutex.
Returns
A Mutex handle to a heap-allocated pthread_mutex_t.
Example
(let [m (mutex-new)] ...) ; => Mutex
Since: Phase T19-C
defn
mutex-lock
(mutex-lock [^borrow m : Mutex] :)
acquire the mutex, blocking until it is available.
Parameters
| m | mutex handle returned by mutex-new |
Example
(mutex-lock m)
Since: Phase T19-C
defn
mutex-unlock
(mutex-unlock [^borrow m : Mutex] :)
release the mutex.
Parameters
| m | mutex handle returned by mutex-new |
Example
(mutex-unlock m)
Since: Phase T19-C
defn
mutex-try-lock
(mutex-try-lock [^borrow m : Mutex] :)
attempt to acquire the mutex without blocking.
Parameters
| m | mutex handle returned by mutex-new |
Returns
true if the mutex was successfully acquired; false if it was already held.
Example
(if (mutex-try-lock m) ...) ; => bool
Since: Phase T19-C
defn
mutex-free
(mutex-free [m : Mutex] :)
destroy the mutex and release its memory.
Parameters
| m | mutex handle returned by mutex-new |
Example
(mutex-free m)
Since: Phase T19-C
defmacro
with-lock
(with-lock [m & body])
run body with the mutex held, releasing it afterwards.
Parameters
| m | a Mutex handle (borrowed; with-lock does not consume or free it) | |
| body | one or more forms; the last one's value is returned |
Returns
The value of the last body form.
Example
(let [m (mutex-new)]
(println (with-lock m (+ 1 41))) ; => 42
(mutex-free m))
Two caveats worth knowing:
`m` is evaluated twice -- once to lock, once to unlock -- so pass a
VARIABLE, not a call. `(with-lock (get-mutex) ...)` would lock one mutex
and unlock whatever the second call returns. A macro cannot bind it once
instead, because `Mutex` is `:linear`: a `let` binding moves the handle,
and the checker then rejects the scope for dropping it unconsumed
(TUR-E0100).
The unlock is not panic-safe. If the body panics, the mutex stays locked.
Guarding against that needs the unlock on an unwind path, which
`catch-unwind` can express at the call site when it matters.
Since: 2026-08-20