Next: , Previous: Special Variables, Up: Threading


11.3 Mutex Support

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)

— Structure: sb-thread:mutex

Class precedence list: mutex, structure-object, t

Mutex type.

— Function: sb-thread:make-mutex &key name value

Create a mutex.

— Function: sb-thread:mutex-name instance

The name of the mutex. Setfable.

— Function: sb-thread:mutex-value instance

The value of the mutex. nil if the mutex is free. Setfable.

— Function: sb-thread:get-mutex mutex &optional new-value wait-p

Acquire mutex, setting it to new-value or some suitable default value if nil. If wait-p is non-NIL and the mutex is in use, sleep until it is available.

— Function: sb-thread:release-mutex mutex

Release mutex by setting it to nil. Wake up threads waiting for this mutex.

— Macro: sb-thread:with-mutex (mutex &key value wait-p) &body body

Acquire mutex for the dynamic scope of body, setting it to new-value or some suitable default value if nil. If wait-p is non-NIL and the mutex is in use, sleep until it is available

— Macro: sb-thread:with-recursive-lock (mutex) &body body

Acquires mutex for the dynamic scope of body. Within that scope further recursive lock attempts for the same mutex succeed. It is allowed to mix with-mutex and with-recursive-lock for the same mutex provided the default value is used for the mutex.