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