1.0.37.10: docs, docs are good
[sbcl.git] / doc / manual / threading.texinfo
1 @node  Threading
2 @comment  node-name,  next,  previous,  up
3 @chapter Threading
4
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
10 SB-THREAD package.
11
12 Threads are part of the default build on x86[-64] Linux only.
13
14 They are also experimentally supported on: x86[-64] Darwin (Mac OS X),
15 x86[-64] FreeBSD, and x86 SunOS (Solaris). On these platforms threads
16 must be explicitly enabled at build-time, see @file{INSTALL} for
17 directions.
18
19 @menu
20 * Threading basics::            
21 * Special Variables::           
22 * Atomic Operations::           
23 * Mutex Support::               
24 * Semaphores::                  
25 * Waitqueue/condition variables::  
26 * Sessions/Debugging::          
27 * Foreign threads::             
28 * Implementation (Linux x86/x86-64)::  
29 @end menu
30
31 @node Threading basics
32 @comment  node-name,  next,  previous,  up
33 @section Threading basics
34
35 @lisp
36 (make-thread (lambda () (write-line "Hello, world")))
37 @end lisp
38
39 @subsection Thread Objects
40
41 @include struct-sb-thread-thread.texinfo
42 @include var-sb-thread-star-current-thread-star.texinfo
43 @include fun-sb-thread-list-all-threads.texinfo
44 @include fun-sb-thread-thread-alive-p.texinfo
45 @include fun-sb-thread-thread-name.texinfo
46
47 @subsection Making, Joining, and Yielding Threads
48
49 @include fun-sb-thread-make-thread.texinfo
50 @include fun-sb-thread-thread-yield.texinfo
51 @include fun-sb-thread-join-thread.texinfo
52
53 @subsection Asynchronous Operations
54
55 @include fun-sb-thread-interrupt-thread.texinfo
56 @include fun-sb-thread-terminate-thread.texinfo
57
58 @subsection Miscellaneous Operations
59
60 @include fun-sb-thread-symbol-value-in-thread.texinfo
61
62 @subsection Error Conditions
63
64 @include condition-sb-thread-thread-error.texinfo
65 @include fun-sb-thread-thread-error-thread.texinfo
66
67 @c @include condition-sb-thread-symbol-value-in-thread-error.texinfo
68 @include condition-sb-thread-interrupt-thread-error.texinfo
69 @include condition-sb-thread-join-thread-error.texinfo
70
71 @node Special Variables
72 @comment  node-name,  next,  previous,  up
73 @section Special Variables
74
75 The interaction of special variables with multiple threads is mostly
76 as one would expect, with behaviour very similar to other
77 implementations.
78
79 @itemize
80 @item
81 global special values are visible across all threads;
82 @item
83 bindings (e.g. using LET) are local to the thread;
84 @item
85 threads do not inherit dynamic bindings from the parent thread
86 @end itemize
87
88 The last point means that
89
90 @lisp
91 (defparameter *x* 0)
92 (let ((*x* 1))
93   (sb-thread:make-thread (lambda () (print *x*))))
94 @end lisp
95
96 prints @code{0} and not @code{1} as of 0.9.6.
97
98 @node Atomic Operations
99 @comment  node-name,  next,  previous,  up
100 @section Atomic Operations
101
102 SBCL provides a few special purpose atomic operations, particularly
103 useful for implementing lockless algorithms.
104
105 @include macro-sb-ext-atomic-decf.texinfo
106 @include macro-sb-ext-atomic-incf.texinfo
107 @include macro-sb-ext-compare-and-swap.texinfo
108
109 @node Mutex Support
110 @comment  node-name,  next,  previous,  up
111 @section Mutex Support
112
113 Mutexes are used for controlling access to a shared resource. One
114 thread is allowed to hold the mutex, others which attempt to take it
115 will be made to wait until it's free. Threads are woken in the order
116 that they go to sleep.
117
118 There isn't a timeout on mutex acquisition, but the usual WITH-TIMEOUT
119 macro (which throws a TIMEOUT condition after n seconds) can be used
120 if you want a bounded wait.
121
122 @lisp
123 (defpackage :demo (:use "CL" "SB-THREAD" "SB-EXT"))
124
125 (in-package :demo)
126
127 (defvar *a-mutex* (make-mutex :name "my lock"))
128
129 (defun thread-fn ()
130   (format t "Thread ~A running ~%" *current-thread*)
131   (with-mutex (*a-mutex*)
132     (format t "Thread ~A got the lock~%" *current-thread*)
133     (sleep (random 5)))
134   (format t "Thread ~A dropped lock, dying now~%" *current-thread*))
135
136 (make-thread #'thread-fn)
137 (make-thread #'thread-fn)
138 @end lisp
139
140 @include struct-sb-thread-mutex.texinfo
141 @include fun-sb-thread-make-mutex.texinfo
142 @include fun-sb-thread-mutex-name.texinfo
143 @include fun-sb-thread-mutex-value.texinfo
144 @include fun-sb-thread-get-mutex.texinfo
145 @include fun-sb-thread-release-mutex.texinfo
146 @include macro-sb-thread-with-mutex.texinfo
147 @include macro-sb-thread-with-recursive-lock.texinfo
148
149 @node Semaphores
150 @comment  node-name,  next,  previous,  up
151 @section Semaphores
152
153 described here should be considered
154 experimental, subject to API changes without notice.
155
156 @include struct-sb-thread-semaphore.texinfo
157 @include fun-sb-thread-make-semaphore.texinfo
158 @include fun-sb-thread-semaphore-count.texinfo
159 @include fun-sb-thread-semaphore-name.texinfo
160 @include fun-sb-thread-signal-semaphore.texinfo
161 @include fun-sb-thread-try-semaphore.texinfo
162 @include fun-sb-thread-wait-on-semaphore.texinfo
163
164 @node Waitqueue/condition variables
165 @comment  node-name,  next,  previous,  up
166 @section Waitqueue/condition variables
167
168 These are based on the POSIX condition variable design, hence the
169 annoyingly CL-conflicting name. For use when you want to check a
170 condition and sleep until it's true. For example: you have a shared
171 queue, a writer process checking ``queue is empty'' and one or more
172 readers that need to know when ``queue is not empty''. It sounds
173 simple, but is astonishingly easy to deadlock if another process runs
174 when you weren't expecting it to.
175
176 There are three components:
177
178 @itemize
179 @item
180 the condition itself (not represented in code)
181
182 @item
183 the condition variable (a.k.a waitqueue) which proxies for it
184
185 @item
186 a lock to hold while testing the condition
187 @end itemize
188
189 Important stuff to be aware of:
190
191 @itemize
192 @item
193 when calling condition-wait, you must hold the mutex. condition-wait
194 will drop the mutex while it waits, and obtain it again before
195 returning for whatever reason;
196
197 @item
198 likewise, you must be holding the mutex around calls to
199 condition-notify;
200
201 @item
202 a process may return from condition-wait in several circumstances: it
203 is not guaranteed that the underlying condition has become true. You
204 must check that the resource is ready for whatever you want to do to
205 it.
206
207 @end itemize
208
209 @lisp
210 (defvar *buffer-queue* (make-waitqueue))
211 (defvar *buffer-lock* (make-mutex :name "buffer lock"))
212
213 (defvar *buffer* (list nil))
214
215 (defun reader ()
216   (with-mutex (*buffer-lock*)
217     (loop
218      (condition-wait *buffer-queue* *buffer-lock*)
219      (loop
220       (unless *buffer* (return))
221       (let ((head (car *buffer*)))
222         (setf *buffer* (cdr *buffer*))
223         (format t "reader ~A woke, read ~A~%"
224                 *current-thread* head))))))
225
226 (defun writer ()
227   (loop
228    (sleep (random 5))
229    (with-mutex (*buffer-lock*)
230      (let ((el (intern
231                 (string (code-char
232                          (+ (char-code #\A) (random 26)))))))
233        (setf *buffer* (cons el *buffer*)))
234      (condition-notify *buffer-queue*))))
235
236 (make-thread #'writer)
237 (make-thread #'reader)
238 (make-thread #'reader)
239 @end lisp
240
241 @include struct-sb-thread-waitqueue.texinfo
242 @include fun-sb-thread-make-waitqueue.texinfo
243 @include fun-sb-thread-waitqueue-name.texinfo
244 @include fun-sb-thread-condition-wait.texinfo
245 @include fun-sb-thread-condition-notify.texinfo
246 @include fun-sb-thread-condition-broadcast.texinfo
247
248 @node Sessions/Debugging
249 @comment  node-name,  next,  previous,  up
250 @section Sessions/Debugging
251
252 If the user has multiple views onto the same Lisp image (for example,
253 using multiple terminals, or a windowing system, or network access)
254 they are typically set up as multiple @dfn{sessions} such that each
255 view has its own collection of foreground/background/stopped threads.
256 A thread which wishes to create a new session can use
257 @code{sb-thread:with-new-session} to remove itself from the current
258 session (which it shares with its parent and siblings) and create a
259 fresh one.
260 # See also @code{sb-thread:make-listener-thread}.
261
262 Within a single session, threads arbitrate between themselves for the
263 user's attention.  A thread may be in one of three notional states:
264 foreground, background, or stopped.  When a background process
265 attempts to print a repl prompt or to enter the debugger, it will stop
266 and print a message saying that it has stopped.  The user at his
267 leisure may switch to that thread to find out what it needs.  If a
268 background thread enters the debugger, selecting any restart will put
269 it back into the background before it resumes.  Arbitration for the
270 input stream is managed by calls to @code{sb-thread:get-foreground}
271 (which may block) and @code{sb-thread:release-foreground}.
272
273 @code{sb-ext:quit} terminates all threads in the current session, but
274 leaves other sessions running.
275
276 @node Foreign threads
277 @comment  node-name,  next,  previous,  up
278 @section Foreign threads
279
280 Direct calls to @code{pthread_create} (instead of @code{MAKE-THREAD})
281 create threads that SBCL is not aware of, these are called foreign
282 threads. Currently, it is not possible to run Lisp code in such
283 threads. This means that the Lisp side signal handlers cannot work.
284 The best solution is to start foreign threads with signals blocked,
285 but since third party libraries may create threads, it is not always
286 feasible to do so. As a workaround, upon receiving a signal in a
287 foreign thread, SBCL changes the thread's sigmask to block all signals
288 that it wants to handle and resends the signal to the current process
289 which should land in a thread that does not block it, that is, a Lisp
290 thread.
291
292 The resignalling trick cannot work for synchronously triggered signals
293 (SIGSEGV and co), take care not to trigger any. Resignalling for
294 synchronously triggered signals in foreign threads is subject to
295 @code{--lose-on-corruption}, see @ref{Runtime Options}.
296
297 @node Implementation (Linux x86/x86-64)
298 @comment  node-name,  next,  previous,  up
299 @section Implementation (Linux x86/x86-64)
300
301 Threading is implemented using pthreads and some Linux specific bits
302 like futexes.
303
304 On x86 the per-thread local bindings for special variables is achieved
305 using the %fs segment register to point to a per-thread storage area.
306 This may cause interesting results if you link to foreign code that
307 expects threading or creates new threads, and the thread library in
308 question uses %fs in an incompatible way. On x86-64 the r12 register
309 has a similar role.
310
311 Queues require the @code{sys_futex()} system call to be available:
312 this is the reason for the NPTL requirement.  We test at runtime that
313 this system call exists.
314
315 Garbage collection is done with the existing Conservative Generational
316 GC.  Allocation is done in small (typically 8k) regions: each thread
317 has its own region so this involves no stopping. However, when a
318 region fills, a lock must be obtained while another is allocated, and
319 when a collection is required, all processes are stopped.  This is
320 achieved by sending them signals, which may make for interesting
321 behaviour if they are interrupted in system calls.  The streams
322 interface is believed to handle the required system call restarting
323 correctly, but this may be a consideration when making other blocking
324 calls e.g. from foreign library code.
325
326 Large amounts of the SBCL library have not been inspected for
327 thread-safety.  Some of the obviously unsafe areas have large locks
328 around them, so compilation and fasl loading, for example, cannot be
329 parallelized.  Work is ongoing in this area.
330
331 A new thread by default is created in the same POSIX process group and
332 session as the thread it was created by.  This has an impact on
333 keyboard interrupt handling: pressing your terminal's intr key
334 (typically @kbd{Control-C}) will interrupt all processes in the
335 foreground process group, including Lisp threads that SBCL considers
336 to be notionally `background'.  This is undesirable, so background
337 threads are set to ignore the SIGINT signal.
338
339 @code{sb-thread:make-listener-thread} in addition to creating a new
340 Lisp session makes a new POSIX session, so that pressing
341 @kbd{Control-C} in one window will not interrupt another listener -
342 this has been found to be embarrassing.