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