2 @comment node-name, next, previous, up
5 SBCL supports a fairly low-level threading interface that maps onto
6 the host operating system's concept of threads or lightweight
7 processes. This means that threads may take advantage of hardware
8 multiprocessing on machines that have more than one CPU, but it does
9 not allow Lisp control of the scheduler. This is found in the
12 This requires Linux (2.6+ or systems with NPTL backports) running on the
13 x86 or x86-64 architecture, or SunOS (Solaris) on the x86. Support for
14 threading on Darwin (Mac OS X) and FreeBSD on the x86 is experimental.
20 * Waitqueue/condition variables::
21 * Sessions/Debugging::
22 * Implementation (Linux x86)::
25 @node Threading basics
26 @comment node-name, next, previous, up
27 @section Threading basics
30 (make-thread (lambda () (write-line "Hello, world")))
33 @include struct-sb-thread-thread.texinfo
34 @include var-sb-thread-star-current-thread-star.texinfo
35 @include fun-sb-thread-make-thread.texinfo
36 @include fun-sb-thread-thread-alive-p.texinfo
37 @include fun-sb-thread-list-all-threads.texinfo
38 @include condition-sb-thread-interrupt-thread-error.texinfo
39 @include fun-sb-thread-interrupt-thread-error-thread.texinfo
40 @include fun-sb-thread-interrupt-thread.texinfo
41 @include fun-sb-thread-terminate-thread.texinfo
43 @node Special Variables
44 @comment node-name, next, previous, up
45 @section Special Variables
47 The interaction of special variables with multiple threads is mostly
48 as one would expect, with behaviour very similar to other
53 global special values are visible across all threads;
55 bindings (e.g. using LET) are local to the thread;
57 threads do not inherit dynamic bindings from the parent thread
60 The last point means that
65 (sb-thread:make-thread (lambda () (print *x*))))
68 prints @code{0} and not @code{1} as of 0.9.6.
71 @comment node-name, next, previous, up
72 @section Mutex Support
74 Mutexes are used for controlling access to a shared resource. One
75 thread is allowed to hold the mutex, others which attempt to take it
76 will be made to wait until it's free. Threads are woken in the order
77 that they go to sleep.
79 There isn't a timeout on mutex acquisition, but the usual WITH-TIMEOUT
80 macro (which throws a TIMEOUT condition after n seconds) can be used
81 if you want a bounded wait.
84 (defpackage :demo (:use "CL" "SB-THREAD" "SB-EXT"))
88 (defvar *a-mutex* (make-mutex :name "my lock"))
91 (format t "Thread ~A running ~%" *current-thread*)
92 (with-mutex (*a-mutex*)
93 (format t "Thread ~A got the lock~%" *current-thread*)
95 (format t "Thread ~A dropped lock, dying now~%" *current-thread*))
97 (make-thread #'thread-fn)
98 (make-thread #'thread-fn)
101 @include struct-sb-thread-mutex.texinfo
102 @include fun-sb-thread-make-mutex.texinfo
103 @include fun-sb-thread-mutex-name.texinfo
104 @include fun-sb-thread-mutex-value.texinfo
105 @include fun-sb-thread-get-mutex.texinfo
106 @include fun-sb-thread-release-mutex.texinfo
107 @include macro-sb-thread-with-mutex.texinfo
108 @include macro-sb-thread-with-recursive-lock.texinfo
110 @node Waitqueue/condition variables
111 @comment node-name, next, previous, up
112 @section Waitqueue/condition variables
114 These are based on the POSIX condition variable design, hence the
115 annoyingly CL-conflicting name. For use when you want to check a
116 condition and sleep until it's true. For example: you have a shared
117 queue, a writer process checking ``queue is empty'' and one or more
118 readers that need to know when ``queue is not empty''. It sounds
119 simple, but is astonishingly easy to deadlock if another process runs
120 when you weren't expecting it to.
122 There are three components:
126 the condition itself (not represented in code)
129 the condition variable (a.k.a waitqueue) which proxies for it
132 a lock to hold while testing the condition
135 Important stuff to be aware of:
139 when calling condition-wait, you must hold the mutex. condition-wait
140 will drop the mutex while it waits, and obtain it again before
141 returning for whatever reason;
144 likewise, you must be holding the mutex around calls to
148 a process may return from condition-wait in several circumstances: it
149 is not guaranteed that the underlying condition has become true. You
150 must check that the resource is ready for whatever you want to do to
156 (defvar *buffer-queue* (make-waitqueue))
157 (defvar *buffer-lock* (make-mutex :name "buffer lock"))
159 (defvar *buffer* (list nil))
162 (with-mutex (*buffer-lock*)
164 (condition-wait *buffer-queue* *buffer-lock*)
166 (unless *buffer* (return))
167 (let ((head (car *buffer*)))
168 (setf *buffer* (cdr *buffer*))
169 (format t "reader ~A woke, read ~A~%"
170 *current-thread* head))))))
175 (with-mutex (*buffer-lock*)
178 (+ (char-code #\A) (random 26)))))))
179 (setf *buffer* (cons el *buffer*)))
180 (condition-notify *buffer-queue*))))
182 (make-thread #'writer)
183 (make-thread #'reader)
184 (make-thread #'reader)
187 @include struct-sb-thread-waitqueue.texinfo
188 @include fun-sb-thread-make-waitqueue.texinfo
189 @include fun-sb-thread-waitqueue-name.texinfo
190 @include fun-sb-thread-condition-wait.texinfo
191 @include fun-sb-thread-condition-notify.texinfo
192 @include fun-sb-thread-condition-broadcast.texinfo
194 @node Sessions/Debugging
195 @comment node-name, next, previous, up
196 @section Sessions/Debugging
198 If the user has multiple views onto the same Lisp image (for example,
199 using multiple terminals, or a windowing system, or network access)
200 they are typically set up as multiple @dfn{sessions} such that each
201 view has its own collection of foreground/background/stopped threads.
202 A thread which wishes to create a new session can use
203 @code{sb-thread:with-new-session} to remove itself from the current
204 session (which it shares with its parent and siblings) and create a
206 # See also @code{sb-thread:make-listener-thread}.
208 Within a single session, threads arbitrate between themselves for the
209 user's attention. A thread may be in one of three notional states:
210 foreground, background, or stopped. When a background process
211 attempts to print a repl prompt or to enter the debugger, it will stop
212 and print a message saying that it has stopped. The user at his
213 leisure may switch to that thread to find out what it needs. If a
214 background thread enters the debugger, selecting any restart will put
215 it back into the background before it resumes. Arbitration for the
216 input stream is managed by calls to @code{sb-thread:get-foreground}
217 (which may block) and @code{sb-thread:release-foreground}.
219 @code{sb-ext:quit} terminates all threads in the current session, but
220 leaves other sessions running.
222 @node Implementation (Linux x86)
223 @comment node-name, next, previous, up
224 @section Implementation (Linux x86/x86-64)
226 Threading is implemented using pthreads and some Linux specific bits
229 On x86 the per-thread local bindings for special variables is achieved
230 using the %fs segment register to point to a per-thread storage area.
231 This may cause interesting results if you link to foreign code that
232 expects threading or creates new threads, and the thread library in
233 question uses %fs in an incompatible way. On x86-64 the r12 register
236 Queues require the @code{sys_futex()} system call to be available:
237 this is the reason for the NPTL requirement. We test at runtime that
238 this system call exists.
240 Garbage collection is done with the existing Conservative Generational
241 GC. Allocation is done in small (typically 8k) regions: each thread
242 has its own region so this involves no stopping. However, when a
243 region fills, a lock must be obtained while another is allocated, and
244 when a collection is required, all processes are stopped. This is
245 achieved by sending them signals, which may make for interesting
246 behaviour if they are interrupted in system calls. The streams
247 interface is believed to handle the required system call restarting
248 correctly, but this may be a consideration when making other blocking
249 calls e.g. from foreign library code.
251 Large amounts of the SBCL library have not been inspected for
252 thread-safety. Some of the obviously unsafe areas have large locks
253 around them, so compilation and fasl loading, for example, cannot be
254 parallelized. Work is ongoing in this area.
256 A new thread by default is created in the same POSIX process group and
257 session as the thread it was created by. This has an impact on
258 keyboard interrupt handling: pressing your terminal's intr key
259 (typically @kbd{Control-C}) will interrupt all processes in the
260 foreground process group, including Lisp threads that SBCL considers
261 to be notionally `background'. This is undesirable, so background
262 threads are set to ignore the SIGINT signal.
264 @code{sb-thread:make-listener-thread} in addition to creating a new
265 Lisp session makes a new POSIX session, so that pressing
266 @kbd{Control-C} in one window will not interrupt another listener -
267 this has been found to be embarrassing.