Next: , Previous: Special Variables, Up: Threading



10.2 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 ()
       (let ((id (current-thread-id)))
         (format t "Thread ~A running ~%" id)
         (with-mutex (*a-mutex*)
           (format t "Thread ~A got the lock~%" id)
           (sleep (random 5)))
         (format t "Thread ~A dropped lock, dying now~%" id)))
     
     (make-thread #'thread-fn)
     (make-thread #'thread-fn)