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