1 ;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
4 Copyright
2006, 2007 Greg Pfeil
6 Distributed under the MIT license
(see LICENSE file
)
9 (in-package #:bordeaux-threads
)
13 (defun %make-thread
(function name
)
14 (mp:make-process function
:name name
:initial-bindings nil
))
16 (defun current-thread ()
19 (defmethod threadp (object)
22 (defun thread-name (thread)
23 (mp:process-name thread
))
25 ;;; Resource contention: locks and recursive locks
27 (defun make-lock (&optional name
)
30 (defun acquire-lock (lock &optional
(wait-p t
))
32 (mp::lock-wait lock
"Lock")
33 (mp::lock-wait-with-timeout lock
"Lock" 0)))
35 (defun release-lock (lock)
36 (setf (mp::lock-process lock
) nil
))
38 (defmacro with-lock-held
((place) &body body
)
39 `(mp:with-lock-held
(,place
) ,@body
))
41 (defmacro with-recursive-lock-held
((place &key timeout
) &body body
)
42 `(mp:with-lock-held
(,place
"Lock Wait" :timeout
,timeout
) ,@body
))
44 ;;; Note that the locks _are_ recursive, but not "balanced", and only
45 ;;; checked if they are being held by the same process by with-lock-held.
46 ;;; The default with-lock-held in bordeaux-mp.lisp sort of works, in that
47 ;;; it will wait for recursive locks by the same process as well.
49 ;;; Resource contention: condition variables
51 ;;; There's some stuff in x86-vm.lisp that might be worth investigating
52 ;;; whether to build on. There's also process-wait and friends.
54 (defstruct condition-var
55 "CMUCL doesn't have conditions, so we need to create our own type."
59 (defun make-condition-variable ()
60 (make-condition-var :lock
(make-lock)))
62 (defun condition-wait (condition-variable lock
)
63 (check-type condition-variable condition-var
)
64 (with-lock-held ((condition-var-lock condition-variable
))
65 (setf (condition-var-active condition-variable
) nil
))
67 (mp:process-wait
"Condition Wait"
68 #'(lambda () (condition-var-active condition-variable
)))
72 (defun condition-notify (condition-variable)
73 (check-type condition-variable condition-var
)
74 (with-lock-held ((condition-var-lock condition-variable
))
75 (setf (condition-var-active condition-variable
) t
))
78 (defun thread-yield ()
83 (defmacro with-timeout
((timeout) &body body
)
84 `(mp:with-timeout
(,timeout
)
87 ;;; Introspection/debugging
92 (defun interrupt-thread (thread function
)
93 (mp:process-interrupt thread function
))
95 (defun destroy-thread (thread)
96 (signal-error-if-current-thread thread
)
97 (mp:destroy-process thread
))
99 (defun thread-alive-p (thread)
100 (mp:process-active-p thread
))