Add INITIAL-BINDINGS keyword argument to MAKE-THREAD.
[bordeaux-threads.git] / src / default-implementations.lisp
blob5a239388a45500f96d86a26710e4ea3b1290fedb
1 ;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
3 (in-package #:bordeaux-threads)
5 ;;; Helper macros
7 (defmacro defdfun (name args doc &body body)
8 (let ((docstring (gensym "DOCSTRING")))
9 `(progn
10 ,(unless (fboundp name)
11 `(defun ,name ,args ,@body))
12 (let ((,docstring (documentation ',name 'function)))
13 (setf (documentation ',name 'function)
14 (if ,docstring
15 (format nil "~a~@[~%~%~a~]" ,doc ,docstring)
16 ,doc))))))
18 (defmacro defdmacro (name args doc &body body)
19 (let ((docstring (gensym "DOCSTRING")))
20 `(progn
21 ,(unless (fboundp name)
22 `(defmacro ,name ,args ,@body))
23 (let ((,docstring (documentation ',name 'function)))
24 (setf (documentation ',name 'function)
25 (if ,docstring
26 (format nil "~a~@[~%~%~a~]" ,doc ,docstring)
27 ,doc))))))
29 ;;; Thread Creation
31 (defdfun make-thread (function &key name
32 (initial-bindings *default-special-bindings*))
33 "Creates and returns a thread named NAME, which will call the
34 function FUNCTION with no arguments: when FUNCTION returns, the
35 thread terminates. NAME defaults to NIL if unsupplied.
37 On systems that do not support multi-threading, MAKE-THREAD will
38 signal an error.
40 The interaction between threads and dynamic variables is in some
41 cases complex, and depends on whether the variable has only a global
42 binding (as established by e.g. DEFVAR/DEFPARAMETER/top-level SETQ)
43 or has been bound locally (e.g. with LET or LET*) in the calling
44 thread.
46 - Global bindings are shared between threads: the initial value of a
47 global variable in the new thread will be the same as in the
48 parent, and an assignment to such a variable in any thread will be
49 visible to all threads in which the global binding is visible.
51 - Local bindings, such as the ones introduced by INITIAL-BINDINGS,
52 are local to the thread they are introduced in, except that
54 - Local bindings in the the caller of MAKE-THREAD may or may not be
55 shared with the new thread that it creates: this is
56 implementation-defined. Portable code should not depend on
57 particular behaviour in this case, nor should it assign to such
58 variables without first rebinding them in the new thread."
59 (%make-thread (binding-default-specials function initial-bindings)
60 name))
62 (defdfun %make-thread (function name)
63 "The actual implementation-dependent function that creates threads."
64 (declare (ignore function name))
65 (error (make-threading-support-error)))
67 (defdfun current-thread ()
68 "Returns the thread object for the calling
69 thread. This is the same kind of object as would be returned by
70 MAKE-THREAD."
71 nil)
73 (defdfun threadp (object)
74 "Returns true if object is a thread, otherwise NIL."
75 (declare (ignore object))
76 nil)
78 (defdfun thread-name (thread)
79 "Returns the name of the thread, as supplied to MAKE-THREAD."
80 (declare (ignore thread))
81 "Main thread")
83 ;;; Resource contention: locks and recursive locks
85 (defdfun make-lock (&optional name)
86 "Creates a lock (a mutex) whose name is NAME. If the system does not
87 support multiple threads this will still return some object, but it
88 may not be used for very much."
89 ;; In CLIM-SYS this is a freshly consed list (NIL). I don't know if
90 ;; there's some good reason it should be said structure or that it
91 ;; be freshly consed - EQ comparison of locks?
92 (declare (ignore name))
93 (list nil))
95 (defdfun acquire-lock (lock &optional wait-p)
96 "Acquire the lock LOCK for the calling thread.
97 WAIT-P governs what happens if the lock is not available: if WAIT-P
98 is true, the calling thread will wait until the lock is available
99 and then acquire it; if WAIT-P is NIL, ACQUIRE-LOCK will return
100 immediately. ACQUIRE-LOCK returns true if the lock was acquired and
101 NIL otherwise.
103 This specification does not define what happens if a thread
104 attempts to acquire a lock that it already holds. For applications
105 that require locks to be safe when acquired recursively, see instead
106 MAKE-RECURSIVE-LOCK and friends."
107 (declare (ignore lock wait-p))
110 (defdfun release-lock (lock)
111 "Release LOCK. It is an error to call this unless
112 the lock has previously been acquired (and not released) by the same
113 thread. If other threads are waiting for the lock, the
114 ACQUIRE-LOCK call in one of them will now be able to continue.
116 This function has no interesting return value."
117 (declare (ignore lock))
118 (values))
120 (defdmacro with-lock-held ((place) &body body)
121 "Evaluates BODY with the lock named by PLACE, the value of which
122 is a lock created by MAKE-LOCK. Before the forms in BODY are
123 evaluated, the lock is acquired as if by using ACQUIRE-LOCK. After the
124 forms in BODY have been evaluated, or if a non-local control transfer
125 is caused (e.g. by THROW or SIGNAL), the lock is released as if by
126 RELEASE-LOCK.
128 Note that if the debugger is entered, it is unspecified whether the
129 lock is released at debugger entry or at debugger exit when execution
130 is restarted."
131 `(when (acquire-lock ,place t)
132 (unwind-protect
133 (locally ,@body)
134 (release-lock ,place))))
136 (defdfun make-recursive-lock (&optional name)
137 "Create and return a recursive lock whose name is NAME. A recursive
138 lock differs from an ordinary lock in that a thread that already
139 holds the recursive lock can acquire it again without blocking. The
140 thread must then release the lock twice before it becomes available
141 for another thread."
142 (declare (ignore name))
143 (list nil))
145 (defdfun acquire-recursive-lock (lock)
146 "As for ACQUIRE-LOCK, but for recursive locks."
147 (declare (ignore lock))
150 (defdfun release-recursive-lock (lock)
151 "Release the recursive LOCK. The lock will only
152 become free after as many Release operations as there have been
153 Acquire operations. See RELEASE-LOCK for other information."
154 (declare (ignore lock))
155 (values))
157 (defdmacro with-recursive-lock-held ((place &key timeout) &body body)
158 "Evaluates BODY with the recursive lock named by PLACE, which is a
159 reference to a recursive lock created by MAKE-RECURSIVE-LOCK. See
160 WITH-LOCK-HELD etc etc"
161 (declare (ignore timeout))
162 `(when (acquire-recursive-lock ,place)
163 (unwind-protect
164 (locally ,@body)
165 (release-recursive-lock ,place))))
167 ;;; Resource contention: condition variables
169 ;;; A condition variable provides a mechanism for threads to put
170 ;;; themselves to sleep while waiting for the state of something to
171 ;;; change, then to be subsequently woken by another thread which has
172 ;;; changed the state.
174 ;;; A condition variable must be used in conjunction with a lock to
175 ;;; protect access to the state of the object of interest. The
176 ;;; procedure is as follows:
178 ;;; Suppose two threads A and B, and some kind of notional event
179 ;;; channel C. A is consuming events in C, and B is producing them.
180 ;;; CV is a condition-variable
182 ;;; 1) A acquires the lock that safeguards access to C
183 ;;; 2) A threads and removes all events that are available in C
184 ;;; 3) When C is empty, A calls CONDITION-WAIT, which atomically
185 ;;; releases the lock and puts A to sleep on CV
186 ;;; 4) Wait to be notified; CONDITION-WAIT will acquire the lock again
187 ;;; before returning
188 ;;; 5) Loop back to step 2, for as long as threading should continue
190 ;;; When B generates an event E, it
191 ;;; 1) acquires the lock guarding C
192 ;;; 2) adds E to the channel
193 ;;; 3) calls CONDITION-NOTIFY on CV to wake any sleeping thread
194 ;;; 4) releases the lock
196 ;;; To avoid the "lost wakeup" problem, the implementation must
197 ;;; guarantee that CONDITION-WAIT in thread A atomically releases the
198 ;;; lock and sleeps. If this is not guaranteed there is the
199 ;;; possibility that thread B can add an event and call
200 ;;; CONDITION-NOTIFY between the lock release and the sleep - in this
201 ;;; case the notify call would not see A, which would be left sleeping
202 ;;; despite there being an event available.
204 (defdfun thread-yield ()
205 "Allows other threads to run. It may be necessary or desirable to
206 call this periodically in some implementations; others may schedule
207 threads automatically. On systems that do not support
208 multi-threading, this does nothing."
209 (values))
211 (defdfun make-condition-variable ()
212 "Returns a new condition-variable object for use
213 with CONDITION-WAIT and CONDITION-NOTIFY."
214 nil)
216 (defdfun condition-wait (condition-variable lock)
217 "Atomically release LOCK and enqueue the calling
218 thread waiting for CONDITION-VARIABLE. The thread will resume when
219 another thread has notified it using CONDITION-NOTIFY; it may also
220 resume if interrupted by some external event or in other
221 implementation-dependent circumstances: the caller must always test
222 on waking that there is threading to be done, instead of assuming
223 that it can go ahead.
225 However and for whatever reason the thread is resumed, the system
226 always reacquires LOCK before returning to the caller. It is an
227 error to call this unless from the thread that holds LOCK.
229 In an implementation that does not support multiple threads, this
230 function signals an error."
231 (declare (ignore condition-variable lock))
232 (error (make-threading-support-error)))
234 (defdfun condition-notify (condition-variable)
235 "Notify at least one of the threads waiting for
236 CONDITION-VARIABLE. It is implementation-dependent whether one or
237 more than one (and possibly all) threads are woken, but if the
238 implementation is capable of waking only a single thread (not all
239 are) this is probably preferable for efficiency reasons. The order
240 of wakeup is unspecified and does not necessarily relate to the
241 order that the threads went to sleep in.
243 CONDITION-NOTIFY has no useful return value. In an implementation
244 that does not support multiple threads, it has no effect."
245 (declare (ignore condition-variable))
246 (values))
248 ;;; Timeouts
250 (defmacro with-timeout ((timeout) &body body)
251 "Execute `BODY' and signal a condition of type TIMEOUT if the execution of
252 BODY does not complete within `TIMEOUT' seconds. On implementations which do not
253 support WITH-TIMEOUT natively and don't support threads either it has no effect."
254 (declare (ignorable timeout))
255 #+thread-support
256 (let ((ok-tag (gensym "OK"))
257 (timeout-tag (gensym "TIMEOUT"))
258 (caller (gensym "CALLER"))
259 (sleeper (gensym "SLEEPER")))
260 `(let (,sleeper)
261 (multiple-value-prog1
262 (catch ',ok-tag
263 (catch ',timeout-tag
264 (let ((,caller (current-thread)))
265 (setf ,sleeper
266 (make-thread #'(lambda ()
267 (sleep ,timeout)
268 (interrupt-thread ,caller
269 #'(lambda ()
270 (ignore-errors
271 (throw ',timeout-tag nil)))))
272 :name (format nil "WITH-TIMEOUT thread serving: ~S."
273 (thread-name ,caller))))
274 (throw ',ok-tag (progn ,@body))))
275 (error 'timeout))
276 (when (thread-alive-p ,sleeper)
277 (destroy-thread ,sleeper)))))
278 #-thread-support
279 `(progn
280 ,@body))
282 ;;; Introspection/debugging
284 ;;; The following functions may be provided for debugging purposes,
285 ;;; but are not advised to be called from normal user code.
287 (defdfun all-threads ()
288 "Returns a sequence of all of the threads. This may not
289 be freshly-allocated, so the caller should not modify it."
290 (error (make-threading-support-error)))
292 (defdfun interrupt-thread (thread function)
293 "Interrupt THREAD and cause it to evaluate FUNCTION
294 before continuing with the interrupted path of execution. This may
295 not be a good idea if THREAD is holding locks or doing anything
296 important. On systems that do not support multiple threads, this
297 function signals an error."
298 (declare (ignore thread function))
299 (error (make-threading-support-error)))
301 (defdfun destroy-thread (thread)
302 "Terminates the thread THREAD, which is an object
303 as returned by MAKE-THREAD. This should be used with caution: it is
304 implementation-defined whether the thread runs cleanup forms or
305 releases its locks first.
307 Destroying the calling thread is an error."
308 (declare (ignore thread))
309 (error (make-threading-support-error)))
311 (defdfun thread-alive-p (thread)
312 "Returns true if THREAD is alive, that is, if
313 DESTROY-THREAD has not been called on it."
314 (declare (ignore thread))
315 (error (make-threading-support-error)))
317 (defdfun thread-join (thread)
318 "Wait until THREAD terminates. If THREAD
319 has already terminated, return immediately."
320 (declare (ignore thread))
321 (error (make-threading-support-error)))