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