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