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