Document scm_with_[un]blocked_asyncs.
[bpt/guile.git] / doc / ref / scheme-scheduling.texi
1 @page
2 @node Scheduling
3 @chapter Threads, Mutexes, Asyncs and Dynamic Roots
4
5 [FIXME: This is pasted in from Tom Lord's original guile.texi chapter
6 plus the Cygnus programmer's manual; it should be *very* carefully
7 reviewed and largely reorganized.]
8
9 @menu
10 * Arbiters:: Synchronization primitives.
11 * Asyncs:: Asynchronous procedure invocation.
12 * Dynamic Roots:: Root frames of execution.
13 * Threads:: Multiple threads of execution.
14 * Fluids:: Thread-local variables.
15 * Futures:: Delayed execution in new threads.
16 * Parallel Forms:: Parallel execution of forms.
17 @end menu
18
19
20 @node Arbiters
21 @section Arbiters
22
23 @cindex arbiters
24
25 @c FIXME::martin: Review me!
26
27 Arbiters are synchronization objects. They are created with
28 @code{make-arbiter}. Two or more threads can synchronize on an arbiter
29 by trying to lock it using @code{try-arbiter}. This call will succeed
30 if no other thread has called @code{try-arbiter} on the arbiter yet,
31 otherwise it will fail and return @code{#f}. Once an arbiter is
32 successfully locked, it cannot be locked by another thread until the
33 thread holding the arbiter calls @code{release-arbiter} to unlock it.
34
35 @deffn {Scheme Procedure} make-arbiter name
36 @deffnx {C Function} scm_make_arbiter (name)
37 Return an object of type arbiter and name @var{name}. Its
38 state is initially unlocked. Arbiters are a way to achieve
39 process synchronization.
40 @end deffn
41
42 @deffn {Scheme Procedure} try-arbiter arb
43 @deffnx {C Function} scm_try_arbiter (arb)
44 Return @code{#t} and lock the arbiter @var{arb} if the arbiter
45 was unlocked. Otherwise, return @code{#f}.
46 @end deffn
47
48 @deffn {Scheme Procedure} release-arbiter arb
49 @deffnx {C Function} scm_release_arbiter (arb)
50 Return @code{#t} and unlock the arbiter @var{arb} if the
51 arbiter was locked. Otherwise, return @code{#f}.
52 @end deffn
53
54
55 @node Asyncs
56 @section Asyncs
57
58 @cindex asyncs
59 @cindex user asyncs
60 @cindex system asyncs
61
62 Asyncs are a means of deferring the excution of Scheme code until it is
63 safe to do so.
64
65 Guile provides two kinds of asyncs that share the basic concept but are
66 otherwise quite different: system asyncs and user asyncs. System asyncs
67 are integrated into the core of Guile and are executed automatically
68 when the system is in a state to allow the execution of Scheme code.
69 For example, it is not possible to execute Scheme code in a POSIX signal
70 handler, but such a signal handler can queue a system async to be
71 executed in the near future, when it is safe to do so.
72
73 System asyncs can also be queued for threads other than the current one.
74 This way, you can cause threads to asynchronously execute arbitrary
75 code.
76
77 User asyncs offer a convenient means of queueing procedures for future
78 execution and triggering this execution. They will not be executed
79 automatically.
80
81 @menu
82 * System asyncs::
83 * User asyncs::
84 @end menu
85
86 @node System asyncs
87 @subsection System asyncs
88
89 To cause the future asynchronous execution of a procedure in a given
90 thread, use @code{system-async-mark}.
91
92 Automatic invocation of system asyncs can be temporarily disabled by
93 calling @code{call-with-blocked-asyncs}. This function works by
94 temporarily increasing the @emph{async blocking level} of the current
95 thread while a given procedure is running. The blocking level starts
96 out at zero, and whenever a safe point is reached, a blocking level
97 greater than zero will prevent the execution of queued asyncs.
98
99 Analogously, the procedure @code{call-with-unblocked-asyncs} will
100 temporarily decrease the blocking level of the current thread. You
101 can use it when you want to disable asyncs by default and only allow
102 them temporarily.
103
104 In addition to the C versions of @code{call-with-blocked-asyncs} and
105 @code{call-with-unblocked-asyncs}, C code can use
106 @code{scm_with_blocked_asyncs} and @code{scm_with_unblocked_asyncs}
107 inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs
108 temporarily.
109
110 @deffn {Scheme Procedure} system-async-mark proc [thread]
111 @deffnx {C Function} scm_system_async_mark (proc)
112 @deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
113 Mark @var{proc} (a procedure with zero arguments) for future execution
114 in @var{thread}. When @var{proc} has already been marked for
115 @var{thread} but has not been executed yet, this call has no effect.
116 When @var{thread} is omitted, the thread that called
117 @code{system-async-mark} is used.
118
119 This procedure is not safe to be called from signal handlers. Use
120 @code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
121 signal handlers.
122 @end deffn
123
124 @c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
125 @c scm_c_call_with_unblocked_asyncs puts "void" into the function
126 @c index. Would prefer to use @deftypefnx if makeinfo allowed that,
127 @c or a @deftypefn with an empty return type argument if it didn't
128 @c introduce an extra space.
129
130 @deffn {Scheme Procedure} call-with-blocked-asyncs proc
131 @deffnx {C Function} scm_call_with_blocked_asyncs (proc)
132 @deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
133 @findex scm_c_call_with_blocked_asyncs
134 Call @var{proc} and block the execution of system asyncs by one level
135 for the current thread while it is running. Return the value returned
136 by @var{proc}. For the first two variants, call @var{proc} with no
137 arguments; for the third, call it with @var{data}.
138 @end deffn
139
140 @deffn {Scheme Procedure} call-with-unblocked-asyncs proc
141 @deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
142 @deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
143 @findex scm_c_call_with_unblocked_asyncs
144 Call @var{proc} and unblock the execution of system asyncs by one
145 level for the current thread while it is running. Return the value
146 returned by @var{proc}. For the first two variants, call @var{proc}
147 with no arguments; for the third, call it with @var{data}.
148 @end deffn
149
150 @deftypefn {C Function} void scm_with_blocked_asyncs ()
151 This function must be used inside a pair of calls to
152 @code{scm_begin_frame} and @code{scm_end_frame} (@pxref{Frames}).
153 During the dynamic extent of the frame, asyncs are blocked by one level.
154 @end deftypefn
155
156 @deftypefn {C Function} void scm_with_unblocked_asyncs ()
157 This function must be used inside a pair of calls to
158 @code{scm_begin_frame} and @code{scm_end_frame} (@pxref{Frames}).
159 During the dynamic extent of the frame, asyncs are unblocked by one
160 level.
161 @end deftypefn
162
163 @node User asyncs
164 @subsection User asyncs
165
166 A user async is a pair of a thunk (a parameterless procedure) and a
167 mark. Setting the mark on a user async will cause the thunk to be
168 executed when the user async is passed to @code{run-asyncs}. Setting
169 the mark more than once is satisfied by one execution of the thunk.
170
171 User asyncs are created with @code{async}. They are marked with
172 @code{async-mark}.
173
174 @deffn {Scheme Procedure} async thunk
175 @deffnx {C Function} scm_async (thunk)
176 Create a new user async for the procedure @var{thunk}.
177 @end deffn
178
179 @deffn {Scheme Procedure} async-mark a
180 @deffnx {C Function} scm_async_mark (a)
181 Mark the user async @var{a} for future execution.
182 @end deffn
183
184 @deffn {Scheme Procedure} run-asyncs list_of_a
185 @deffnx {C Function} scm_run_asyncs (list_of_a)
186 Execute all thunks from the marked asyncs of the list @var{list_of_a}.
187 @end deffn
188
189
190 @node Dynamic Roots
191 @section Dynamic Roots
192 @cindex dynamic roots
193
194 A @dfn{dynamic root} is a root frame of Scheme evaluation.
195 The top-level repl, for example, is an instance of a dynamic root.
196
197 Each dynamic root has its own chain of dynamic-wind information. Each
198 has its own set of continuations, jump-buffers, and pending CATCH
199 statements which are inaccessible from the dynamic scope of any
200 other dynamic root.
201
202 In a thread-based system, each thread has its own dynamic root. Therefore,
203 continuations created by one thread may not be invoked by another.
204
205 Even in a single-threaded system, it is sometimes useful to create a new
206 dynamic root. For example, if you want to apply a procedure, but to
207 not allow that procedure to capture the current continuation, calling
208 the procedure under a new dynamic root will do the job.
209
210 @deffn {Scheme Procedure} call-with-dynamic-root thunk handler
211 @deffnx {C Function} scm_call_with_dynamic_root (thunk, handler)
212 Evaluate @code{(thunk)} in a new dynamic context, returning its value.
213
214 If an error occurs during evaluation, apply @var{handler} to the
215 arguments to the throw, just as @code{throw} would. If this happens,
216 @var{handler} is called outside the scope of the new root -- it is
217 called in the same dynamic context in which
218 @code{call-with-dynamic-root} was evaluated.
219
220 If @var{thunk} captures a continuation, the continuation is rooted at
221 the call to @var{thunk}. In particular, the call to
222 @code{call-with-dynamic-root} is not captured. Therefore,
223 @code{call-with-dynamic-root} always returns at most one time.
224
225 Before calling @var{thunk}, the dynamic-wind chain is un-wound back to
226 the root and a new chain started for @var{thunk}. Therefore, this call
227 may not do what you expect:
228
229 @lisp
230 ;; Almost certainly a bug:
231 (with-output-to-port
232 some-port
233
234 (lambda ()
235 (call-with-dynamic-root
236 (lambda ()
237 (display 'fnord)
238 (newline))
239 (lambda (errcode) errcode))))
240 @end lisp
241
242 The problem is, on what port will @samp{fnord} be displayed? You
243 might expect that because of the @code{with-output-to-port} that
244 it will be displayed on the port bound to @code{some-port}. But it
245 probably won't -- before evaluating the thunk, dynamic winds are
246 unwound, including those created by @code{with-output-to-port}.
247 So, the standard output port will have been re-set to its default value
248 before @code{display} is evaluated.
249
250 (This function was added to Guile mostly to help calls to functions in C
251 libraries that can not tolerate non-local exits or calls that return
252 multiple times. If such functions call back to the interpreter, it should
253 be under a new dynamic root.)
254 @end deffn
255
256
257 @deffn {Scheme Procedure} dynamic-root
258 @deffnx {C Function} scm_dynamic_root ()
259 Return an object representing the current dynamic root.
260
261 These objects are only useful for comparison using @code{eq?}.
262 They are currently represented as numbers, but your code should
263 in no way depend on this.
264 @end deffn
265
266 @c begin (scm-doc-string "boot-9.scm" "quit")
267 @deffn {Scheme Procedure} quit [exit_val]
268 Throw back to the error handler of the current dynamic root.
269
270 If integer @var{exit_val} is specified and if Guile is being used
271 stand-alone and if quit is called from the initial dynamic-root,
272 @var{exit_val} becomes the exit status of the Guile process and the
273 process exits.
274 @end deffn
275
276 When Guile is run interactively, errors are caught from within the
277 read-eval-print loop. An error message will be printed and @code{abort}
278 called. A default set of signal handlers is installed, e.g., to allow
279 user interrupt of the interpreter.
280
281 It is possible to switch to a "batch mode", in which the interpreter
282 will terminate after an error and in which all signals cause their
283 default actions. Switching to batch mode causes any handlers installed
284 from Scheme code to be removed. An example of where this is useful is
285 after forking a new process intended to run non-interactively.
286
287 @c begin (scm-doc-string "boot-9.scm" "batch-mode?")
288 @deffn {Scheme Procedure} batch-mode?
289 Returns a boolean indicating whether the interpreter is in batch mode.
290 @end deffn
291
292 @c begin (scm-doc-string "boot-9.scm" "set-batch-mode?!")
293 @deffn {Scheme Procedure} set-batch-mode?! arg
294 If @var{arg} is true, switches the interpreter to batch mode.
295 The @code{#f} case has not been implemented.
296 @end deffn
297
298 @node Threads
299 @section Threads
300 @cindex threads
301 @cindex Guile threads
302 @cindex POSIX threads
303
304 Guile threads are implemented using POSIX threads, they run
305 pre-emptively and concurrently through both Scheme code and system
306 calls. The only exception is for garbage collection, where all
307 threads must rendezvous.
308
309 @menu
310 * Low level thread primitives::
311 * Higher level thread procedures::
312 * C level thread interface::
313 @end menu
314
315
316 @node Low level thread primitives
317 @subsection Low level thread primitives
318
319 @c NJFIXME no current mechanism for making sure that these docstrings
320 @c are in sync.
321
322 @c begin (texi-doc-string "guile" "call-with-new-thread")
323 @deffn {Scheme Procedure} call-with-new-thread thunk error-handler
324 Evaluate @code{(thunk)} in a new thread, and new dynamic context,
325 returning a new thread object representing the thread.
326
327 If an error occurs during evaluation, call error-handler, passing it
328 an error code. If this happens, the error-handler is called outside
329 the scope of the new root -- it is called in the same dynamic context
330 in which with-new-thread was evaluated, but not in the caller's
331 thread.
332
333 All the evaluation rules for dynamic roots apply to threads.
334 @end deffn
335
336 @c begin (texi-doc-string "guile" "join-thread")
337 @deffn {Scheme Procedure} join-thread thread
338 Suspend execution of the calling thread until the target @var{thread}
339 terminates, unless the target @var{thread} has already terminated.
340 @end deffn
341
342 @c begin (texi-doc-string "guile" "yield")
343 @deffn {Scheme Procedure} yield
344 If one or more threads are waiting to execute, calling yield forces an
345 immediate context switch to one of them. Otherwise, yield has no effect.
346 @end deffn
347
348 @c begin (texi-doc-string "guile" "make-mutex")
349 @deffn {Scheme Procedure} make-mutex
350 Create a new mutex object.
351 @end deffn
352
353 @c begin (texi-doc-string "guile" "lock-mutex")
354 @deffn {Scheme Procedure} lock-mutex mutex
355 Lock @var{mutex}. If the mutex is already locked, the calling thread
356 blocks until the mutex becomes available. The function returns when
357 the calling thread owns the lock on @var{mutex}. Locking a mutex that
358 a thread already owns will succeed right away and will not block the
359 thread. That is, Guile's mutexes are @emph{recursive}.
360
361 When a system async is activated for a thread that is blocked in a
362 call to @code{lock-mutex}, the waiting is interrupted and the async is
363 executed. When the async returns, the waiting is resumed.
364 @end deffn
365
366 @deffn {Scheme Procedure} try-mutex mutex
367 Try to lock @var{mutex}. If the mutex is already locked by someone
368 else, return @code{#f}. Else lock the mutex and return @code{#t}.
369 @end deffn
370
371 @c begin (texi-doc-string "guile" "unlock-mutex")
372 @deffn {Scheme Procedure} unlock-mutex mutex
373 Unlocks @var{mutex} if the calling thread owns the lock on
374 @var{mutex}. Calling unlock-mutex on a mutex not owned by the current
375 thread results in undefined behaviour. Once a mutex has been unlocked,
376 one thread blocked on @var{mutex} is awakened and grabs the mutex
377 lock. Every call to @code{lock-mutex} by this thread must be matched
378 with a call to @code{unlock-mutex}. Only the last call to
379 @code{unlock-mutex} will actually unlock the mutex.
380 @end deffn
381
382 @c begin (texi-doc-string "guile" "make-condition-variable")
383 @deffn {Scheme Procedure} make-condition-variable
384 Make a new condition variable.
385 @end deffn
386
387 @c begin (texi-doc-string "guile" "wait-condition-variable")
388 @deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time]
389 Wait until @var{cond-var} has been signalled. While waiting,
390 @var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
391 is locked again when this function returns. When @var{time} is given,
392 it specifies a point in time where the waiting should be aborted. It
393 can be either a integer as returned by @code{current-time} or a pair
394 as returned by @code{gettimeofday}. When the waiting is aborted,
395 @code{#f} is returned. When the condition variable has in fact been
396 signalled, @code{#t} is returned. The mutex is re-locked in any case
397 before @code{wait-condition-variable} returns.
398
399 When a system async is activated for a thread that is blocked in a
400 call to @code{wait-condition-variable}, the waiting is interrupted,
401 the mutex is locked, and the async is executed. When the async
402 returns, the mutex is unlocked again and the waiting is resumed.
403 @end deffn
404
405 @c begin (texi-doc-string "guile" "signal-condition-variable")
406 @deffn {Scheme Procedure} signal-condition-variable cond-var
407 Wake up one thread that is waiting for @var{cv}.
408 @end deffn
409
410 @c begin (texi-doc-string "guile" "broadcast-condition-variable")
411 @deffn {Scheme Procedure} broadcast-condition-variable cond-var
412 Wake up all threads that are waiting for @var{cv}.
413 @end deffn
414
415 @node Higher level thread procedures
416 @subsection Higher level thread procedures
417
418 @c new by ttn, needs review
419
420 Higher level thread procedures are available by loading the
421 @code{(ice-9 threads)} module. These provide standardized
422 thread creation and mutex interaction.
423
424 @deffn macro make-thread proc [args@dots{}]
425 Apply @var{proc} to @var{args} in a new thread formed by
426 @code{call-with-new-thread} using a default error handler that display
427 the error to the current error port.
428 @end deffn
429
430 @deffn macro begin-thread first [rest@dots{}]
431 Evaluate forms @var{first} and @var{rest} in a new thread formed by
432 @code{call-with-new-thread} using a default error handler that display
433 the error to the current error port.
434 @end deffn
435
436 @deffn macro with-mutex m [body@dots{}]
437 Lock mutex @var{m}, evaluate @var{body}, and then unlock @var{m}.
438 These sub-operations form the branches of a @code{dynamic-wind}.
439 @end deffn
440
441 @deffn macro monitor first [rest@dots{}]
442 Evaluate forms @var{first} and @var{rest} under a newly created
443 anonymous mutex, using @code{with-mutex}.
444 @end deffn
445
446 @node C level thread interface
447 @subsection C level thread interface
448
449 You can create and manage threads, mutexes, and condition variables
450 with the C versions of the primitives above. For example, you can
451 create a mutex with @code{scm_make_mutex} and lock it with
452 @code{scm_lock_mutex}. In addition to these primitives there is also
453 a second set of primitives for threading related things. These
454 functions and data types are only available from C and can not be
455 mixed with the first set from above. However, they might be more
456 efficient and can be used in situations where Scheme data types are
457 not allowed or are inconvenient to use.
458
459 Furthermore, they are the primitives that Guile relies on for its own
460 higher level threads. By reimplementing them, you can adapt Guile to
461 different low-level thread implementations.
462
463 C code in a thread must call a libguile function periodically. When
464 one thread finds garbage collection is required, it waits for all
465 threads to rendezvous before doing that GC. Such a rendezvous is
466 checked within libguile functions. If C code wants to sleep or block
467 in a thread it should use one of the libguile functions provided.
468
469 Only threads created by Guile can use the libguile functions. Threads
470 created directly with say @code{pthread_create} are unknown to Guile
471 and they cannot call libguile. The stack in such foreign threads is
472 not scanned during GC, so @code{SCM} values generally cannot be held
473 there.
474
475 @c FIXME:
476 @c
477 @c Describe SCM_TICK which can be called if no other libguile
478 @c function is being used by a C function.
479 @c
480 @c Describe "Guile mode", which a thread can enter and exit. There
481 @c are no functions for doing this yet.
482 @c
483 @c When in guile mode a thread can call libguile, is subject to the
484 @c tick rule, and its stack is scanned. When not in guile mode it
485 @c cannot call libguile, it doesn't have to tick, and its stack is
486 @c not scanned. The strange guile control flow things like
487 @c exceptions, continuations and asyncs only occur when in guile
488 @c mode.
489 @c
490 @c When guile mode is exited, the portion of the stack allocated
491 @c while it was in guile mode is still scanned. This portion may not
492 @c be modified when outside guile mode. The stack ends up
493 @c partitioned into alternating guile and non-guile regions.
494 @c
495 @c Leaving guile mode is convenient when running an extended
496 @c calculation not involving guile, since one doesn't need to worry
497 @c about SCM_TICK calls.
498
499
500 @deftp {C Data Type} scm_t_thread
501 This data type represents a thread, to be used with scm_thread_create,
502 etc.
503 @end deftp
504
505 @deftypefn {C Function} int scm_thread_create (scm_t_thread *t, void (*proc)(void *), void *data)
506 Create a new thread that will start by calling @var{proc}, passing it
507 @var{data}. A handle for the new thread is stored in @var{t}, which
508 must be non-NULL. The thread terminated when @var{proc} returns.
509 When the thread has not been detached, its handle remains valid after
510 is has terminated so that it can be used with @var{scm_thread_join},
511 for example. When it has been detached, the handle becomes invalid as
512 soon as the thread terminates.
513 @end deftypefn
514
515 @deftypefn {C Function} void scm_thread_detach (scm_t_thread t)
516 Detach the thread @var{t}. See @code{scm_thread_create}.
517 @end deftypefn
518
519 @deftypefn {C Function} void scm_thread_join (scm_t_thread t)
520 Wait for thread @var{t} to terminate. The thread must not have been
521 detached at the time that @code{scm_thread_join} is called, but it
522 might have been detached by the time it terminates.
523 @end deftypefn
524
525 @deftypefn {C Function} scm_t_thread scm_thread_self ()
526 Return the handle of the calling thread.
527 @end deftypefn
528
529 @deftp {C Data Type} scm_t_mutex
530 This data type represents a mutex, to be used with scm_mutex_init,
531 etc.
532 @end deftp
533
534 @deftypefn {C Function} void scm_mutex_init (scm_t_mutex *m)
535 Initialize the mutex structure pointed to by @var{m}.
536 @end deftypefn
537
538 @deftypefn {C Function} void scm_mutex_destroy (scm_t_mutex *m)
539 Deallocate all resources associated with @var{m}.
540 @end deftypefn
541
542 @deftypefn {C Function} void scm_mutex_lock (scm_t_mutex *m)
543 Lock the mutex @var{m}. When it is already locked by a different
544 thread, wait until it becomes available. Locking a mutex that is
545 already locked by the current threads is not allowd and results in
546 undefined behavior. The mutices are not guaranteed to be fair. That
547 is, a thread that attempts a lock after yourself might be granted it
548 before you.
549 @end deftypefn
550
551 @deftypefn {C Function} int scm_mutex_trylock (scm_t_mutex *m)
552 Lock @var{m} as with @code{scm_mutex_lock} but don't wait when this
553 does succeed immediately. Returns non-zero when the mutex could in
554 fact be locked , and zero when it is already locked by some other
555 thread.
556 @end deftypefn
557
558 @deftypefn {C Function} void scm_mutex_unlock (scm_t_mutex *m)
559 Unlock the mutex @var{m}. The mutex must have been locked by the
560 current thread, else the behavior is undefined.
561 @end deftypefn
562
563 @deftp {C Data Type} scm_t_cond
564 This data type represents a condition variable, to be used with
565 scm_cond_init, etc.
566 @end deftp
567
568 @deftypefn {C Function} void scm_cond_init (scm_t_cond *c)
569 Initialize the mutex structure pointed to by @var{c}.
570 @end deftypefn
571
572 @deftypefn {C Function} void scm_cond_destroy (scm_t_cond *c)
573 Deallocate all resources associated with @var{c}.
574 @end deftypefn
575
576 @deftypefn {C Function} void scm_cond_wait (scm_t_cond *c, scm_t_mutex *m)
577 Wait for @var{c} to be signalled. While waiting @var{m} is unlocked
578 and locked again before @code{scm_cond_wait} returns.
579 @end deftypefn
580
581 @deftypefn {C Function} void scm_cond_timedwait (scm_t_cond *c, scm_t_mutex *m, timespec *abstime)
582 Wait for @var{c} to be signalled as with @code{scm_cond_wait} but
583 don't wait longer than the point in time specified by @var{abstime}.
584 when the waiting is aborted, zero is returned; non-zero else.
585 @end deftypefn
586
587 @deftypefn {C Function} void scm_cond_signal (scm_t_cond *c)
588 Signal the condition variable @var{c}. When one or more threads are
589 waiting for it to be signalled, select one arbitrarily and let its
590 wait succeed.
591 @end deftypefn
592
593 @deftypefn {C Function} void scm_cond_broadcast (scm_t_cond *c)
594 Signal the condition variable @var{c}. When there are threads waiting
595 for it to be signalled, wake them all up and make all their waits
596 succeed.
597 @end deftypefn
598
599 @deftp {C Type} scm_t_key
600 This type represents a key for a thread-specific value.
601 @end deftp
602
603 @deftypefn {C Function} void scm_key_create (scm_t_key *keyp)
604 Create a new key for a thread-specific value. Each thread has its own
605 value associated to such a handle. The new handle is stored into
606 @var{keyp}, which must be non-NULL.
607 @end deftypefn
608
609 @deftypefn {C Function} void scm_key_delete (scm_t_key key)
610 This function makes @var{key} invalid as a key for thread-specific data.
611 @end deftypefn
612
613 @deftypefn {C Function} void scm_key_setspecific (scm_t_key key, const void *value)
614 Associate @var{value} with @var{key} in the calling thread.
615 @end deftypefn
616
617 @deftypefn {C Function} int scm_key_getspecific (scm_t_key key)
618 Return the value currently associated with @var{key} in the calling
619 thread. When @code{scm_key_setspecific} has not yet been called in
620 this thread with this key, @code{NULL} is returned.
621 @end deftypefn
622
623 @deftypefn {C Function} int scm_thread_select (...)
624 This function does the same thing as the system's @code{select}
625 function, but in a way that is friendly to the thread implementation.
626 You should call it in preference to the system @code{select}.
627 @end deftypefn
628
629 @node Fluids
630 @section Fluids
631
632 @cindex fluids
633
634 @c FIXME::martin: Review me!
635
636 Fluids are objects to store values in. They have a few properties
637 which make them useful in certain situations: Fluids can have one
638 value per dynamic root (@pxref{Dynamic Roots}), so that changes to the
639 value in a fluid are only visible in the same dynamic root. Since
640 threads are executed in separate dynamic roots, fluids can be used for
641 thread local storage (@pxref{Threads}).
642
643 Fluids can be used to simulate the desirable effects of dynamically
644 scoped variables. Dynamically scoped variables are useful when you
645 want to set a variable to a value during some dynamic extent in the
646 execution of your program and have them revert to their original value
647 when the control flow is outside of this dynamic extent. See the
648 description of @code{with-fluids} below for details.
649
650 New fluids are created with @code{make-fluid} and @code{fluid?} is
651 used for testing whether an object is actually a fluid. The values
652 stored in a fluid can be accessed with @code{fluid-ref} and
653 @code{fluid-set!}.
654
655 @deffn {Scheme Procedure} make-fluid
656 @deffnx {C Function} scm_make_fluid ()
657 Return a newly created fluid.
658 Fluids are objects of a certain type (a smob) that can hold one SCM
659 value per dynamic root. That is, modifications to this value are
660 only visible to code that executes within the same dynamic root as
661 the modifying code. When a new dynamic root is constructed, it
662 inherits the values from its parent. Because each thread executes
663 in its own dynamic root, you can use fluids for thread local storage.
664 @end deffn
665
666 @deffn {Scheme Procedure} fluid? obj
667 @deffnx {C Function} scm_fluid_p (obj)
668 Return @code{#t} iff @var{obj} is a fluid; otherwise, return
669 @code{#f}.
670 @end deffn
671
672 @deffn {Scheme Procedure} fluid-ref fluid
673 @deffnx {C Function} scm_fluid_ref (fluid)
674 Return the value associated with @var{fluid} in the current
675 dynamic root. If @var{fluid} has not been set, then return
676 @code{#f}.
677 @end deffn
678
679 @deffn {Scheme Procedure} fluid-set! fluid value
680 @deffnx {C Function} scm_fluid_set_x (fluid, value)
681 Set the value associated with @var{fluid} in the current dynamic root.
682 @end deffn
683
684 @code{with-fluids*} temporarily changes the values of one or more fluids,
685 so that the given procedure and each procedure called by it access the
686 given values. After the procedure returns, the old values are restored.
687
688 @deffn {Scheme Procedure} with-fluids* fluids values thunk
689 @deffnx {C Function} scm_with_fluids (fluids, values, thunk)
690 Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
691 @var{fluids} must be a list of fluids and @var{values} must be the
692 same number of their values to be applied. Each substitution is done
693 in the order given. @var{thunk} must be a procedure with no argument.
694 it is called inside a @code{dynamic-wind} and the fluids are
695 set/restored when control enter or leaves the established dynamic
696 extent.
697 @end deffn
698
699 @deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
700 Execute @var{body...} while each @var{fluid} is set to the
701 corresponding @var{value}. Both @var{fluid} and @var{value} are
702 evaluated and @var{fluid} must yield a fluid. @var{body...} is
703 executed inside a @code{dynamic-wind} and the fluids are set/restored
704 when control enter or leaves the established dynamic extent.
705 @end deffn
706
707
708 @node Futures
709 @section Futures
710 @cindex futures
711
712 Futures are a convenient way to run a calculation in a new thread, and
713 only wait for the result when it's actually needed.
714
715 Futures are similar to promises (@pxref{Delayed Evaluation}), in that
716 they allow mainline code to continue immediately. But @code{delay}
717 doesn't evaluate at all until forced, whereas @code{future} starts
718 immediately in a new thread.
719
720 @deffn {syntax} future expr
721 Begin evaluating @var{expr} in a new thread, and return a ``future''
722 object representing the calculation.
723 @end deffn
724
725 @deffn {Scheme Procedure} make-future thunk
726 @deffnx {C Function} scm_make_future (thunk)
727 Begin evaluating the call @code{(@var{thunk})} in a new thread, and
728 return a ``future'' object representing the calculation.
729 @end deffn
730
731 @deffn {Scheme Procedure} future-ref f
732 @deffnx {C Function} scm_future_ref (f)
733 Return the value computed by the future @var{f}. If @var{f} has not
734 yet finished executing then wait for it to do so.
735 @end deffn
736
737
738 @node Parallel Forms
739 @section Parallel forms
740 @cindex parallel forms
741
742 The functions described in this section are available from
743
744 @example
745 (use-modules (ice-9 threads))
746 @end example
747
748 @deffn syntax parallel expr1 @dots{} exprN
749 Evaluate each @var{expr} expression in parallel, each in a new thread.
750 Return the results as a set of @var{N} multiple values
751 (@pxref{Multiple Values}).
752 @end deffn
753
754 @deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
755 Evaluate each @var{expr} in parallel, each in a new thread, then bind
756 the results to the corresponding @var{var} variables and evaluate
757 @var{body}.
758
759 @code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
760 expressions for the bindings are evaluated in parallel.
761 @end deffn
762
763 @deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
764 @deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
765 Call @var{proc} on the elements of the given lists. @code{par-map}
766 returns a list comprising the return values from @var{proc}.
767 @code{par-for-each} returns an unspecified value, but waits for all
768 calls to complete.
769
770 The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
771 @var{elemN})}, where each @var{elem} is from the corresponding
772 @var{lst}. Each @var{lst} must be the same length. The calls are
773 made in parallel, each in a new thread.
774
775 These functions are like @code{map} and @code{for-each} (@pxref{List
776 Mapping}), but make their @var{proc} calls in parallel.
777 @end deffn
778
779 @deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
780 @deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
781 Call @var{proc} on the elements of the given lists, in the same way as
782 @code{par-map} and @code{par-for-each} above, but use no more than
783 @var{n} new threads at any one time. The order in which calls are
784 initiated within that threads limit is unspecified.
785
786 These functions are good for controlling resource consumption if
787 @var{proc} calls might be costly, or if there are many to be made. On
788 a dual-CPU system for instance @math{@var{n}=4} might be enough to
789 keep the CPUs utilized, and not consume too much memory.
790 @end deffn
791
792 @deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
793 Apply @var{pproc} to the elements of the given lists, and apply
794 @var{sproc} to each result returned by @var{pproc}. The final return
795 value is unspecified, but all calls will have been completed before
796 returning.
797
798 The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
799 @var{elemN}))}, where each @var{elem} is from the corresponding
800 @var{lst}. Each @var{lst} must have the same number of elements.
801
802 The @var{pproc} calls are made in parallel, in new threads. No more
803 than @var{n} new threads are used at any one time. The order in which
804 @var{pproc} calls are initiated within that limit is unspecified.
805
806 The @var{sproc} calls are made serially, in list element order, one at
807 a time. @var{pproc} calls on later elements may execute in parallel
808 with the @var{sproc} calls. Exactly which thread makes each
809 @var{sproc} call is unspecified.
810
811 This function is designed for individual calculations that can be done
812 in parallel, but with results needing to be handled serially, for
813 instance to write them to a file. The @var{n} limit on threads
814 controls system resource usage when there are many calculations or
815 when they might be costly.
816
817 It will be seen that @code{n-for-each-par-map} is like a combination
818 of @code{n-par-map} and @code{for-each},
819
820 @example
821 (for-each sproc (n-par-map pproc lst1 ... lstN))
822 @end example
823
824 @noindent
825 But the actual implementation is more efficient since each @var{sproc}
826 call, in turn, can be initiated once the relevant @var{pproc} call has
827 completed, it doesn't need to wait for all to finish.
828 @end deffn
829
830
831 @c Local Variables:
832 @c TeX-master: "guile.texi"
833 @c End: