Next: Waitqueue/condition variables, Previous: Special Variables, Up: Threading
Mutexes are used for controlling access to a shared resource. One thread is allowed to hold the mutex, others which attempt to take it will be made to wait until it's free. Threads are woken in the order that they go to sleep.
There isn't a timeout on mutex acquisition, but the usual WITH-TIMEOUT macro (which throws a TIMEOUT condition after n seconds) can be used if you want a bounded wait.
(defpackage :demo (:use "CL" "SB-THREAD" "SB-EXT"))
(in-package :demo)
(defvar *a-mutex* (make-mutex :name "my lock"))
(defun thread-fn ()
(format t "Thread ~A running ~%" *current-thread*)
(with-mutex (*a-mutex*)
(format t "Thread ~A got the lock~%" *current-thread*)
(sleep (random 5)))
(format t "Thread ~A dropped lock, dying now~%" *current-thread*)))
(make-thread #'thread-fn)
(make-thread #'thread-fn)
Acquire
mutex, setting it tonew-valueor some suitable default value ifnil. Ifwait-pis non-NIL and the mutex is in use, sleep until it is available
Release
mutexby setting it tonil. Wake up threads waiting for this mutex.