2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
9 @section Threads, Mutexes, Asyncs and Dynamic Roots
11 [FIXME: This is pasted in from Tom Lord's original guile.texi chapter
12 plus the Cygnus programmer's manual; it should be *very* carefully
13 reviewed and largely reorganized.]
16 * Arbiters:: Synchronization primitives.
17 * Asyncs:: Asynchronous procedure invocation.
18 * Dynamic Roots:: Root frames of execution.
19 * Threads:: Multiple threads of execution.
20 * Fluids:: Thread-local variables.
21 * Futures:: Delayed execution in new threads.
22 * Parallel Forms:: Parallel execution of forms.
31 @c FIXME::martin: Review me!
33 Arbiters are synchronization objects. They are created with
34 @code{make-arbiter}. Two or more threads can synchronize on an arbiter
35 by trying to lock it using @code{try-arbiter}. This call will succeed
36 if no other thread has called @code{try-arbiter} on the arbiter yet,
37 otherwise it will fail and return @code{#f}. Once an arbiter is
38 successfully locked, it cannot be locked by another thread until the
39 thread holding the arbiter calls @code{release-arbiter} to unlock it.
41 @deffn {Scheme Procedure} make-arbiter name
42 @deffnx {C Function} scm_make_arbiter (name)
43 Return an object of type arbiter and name @var{name}. Its
44 state is initially unlocked. Arbiters are a way to achieve
45 process synchronization.
48 @deffn {Scheme Procedure} try-arbiter arb
49 @deffnx {C Function} scm_try_arbiter (arb)
50 Return @code{#t} and lock the arbiter @var{arb} if the arbiter
51 was unlocked. Otherwise, return @code{#f}.
54 @deffn {Scheme Procedure} release-arbiter arb
55 @deffnx {C Function} scm_release_arbiter (arb)
56 Return @code{#t} and unlock the arbiter @var{arb} if the
57 arbiter was locked. Otherwise, return @code{#f}.
68 Asyncs are a means of deferring the excution of Scheme code until it is
71 Guile provides two kinds of asyncs that share the basic concept but are
72 otherwise quite different: system asyncs and user asyncs. System asyncs
73 are integrated into the core of Guile and are executed automatically
74 when the system is in a state to allow the execution of Scheme code.
75 For example, it is not possible to execute Scheme code in a POSIX signal
76 handler, but such a signal handler can queue a system async to be
77 executed in the near future, when it is safe to do so.
79 System asyncs can also be queued for threads other than the current one.
80 This way, you can cause threads to asynchronously execute arbitrary
83 User asyncs offer a convenient means of queueing procedures for future
84 execution and triggering this execution. They will not be executed
93 @subsubsection System asyncs
95 To cause the future asynchronous execution of a procedure in a given
96 thread, use @code{system-async-mark}.
98 Automatic invocation of system asyncs can be temporarily disabled by
99 calling @code{call-with-blocked-asyncs}. This function works by
100 temporarily increasing the @emph{async blocking level} of the current
101 thread while a given procedure is running. The blocking level starts
102 out at zero, and whenever a safe point is reached, a blocking level
103 greater than zero will prevent the execution of queued asyncs.
105 Analogously, the procedure @code{call-with-unblocked-asyncs} will
106 temporarily decrease the blocking level of the current thread. You
107 can use it when you want to disable asyncs by default and only allow
110 In addition to the C versions of @code{call-with-blocked-asyncs} and
111 @code{call-with-unblocked-asyncs}, C code can use
112 @code{scm_with_blocked_asyncs} and @code{scm_with_unblocked_asyncs}
113 inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs
116 @deffn {Scheme Procedure} system-async-mark proc [thread]
117 @deffnx {C Function} scm_system_async_mark (proc)
118 @deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
119 Mark @var{proc} (a procedure with zero arguments) for future execution
120 in @var{thread}. When @var{proc} has already been marked for
121 @var{thread} but has not been executed yet, this call has no effect.
122 When @var{thread} is omitted, the thread that called
123 @code{system-async-mark} is used.
125 This procedure is not safe to be called from signal handlers. Use
126 @code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
130 @c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
131 @c scm_c_call_with_unblocked_asyncs puts "void" into the function
132 @c index. Would prefer to use @deftypefnx if makeinfo allowed that,
133 @c or a @deftypefn with an empty return type argument if it didn't
134 @c introduce an extra space.
136 @deffn {Scheme Procedure} call-with-blocked-asyncs proc
137 @deffnx {C Function} scm_call_with_blocked_asyncs (proc)
138 @deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
139 @findex scm_c_call_with_blocked_asyncs
140 Call @var{proc} and block the execution of system asyncs by one level
141 for the current thread while it is running. Return the value returned
142 by @var{proc}. For the first two variants, call @var{proc} with no
143 arguments; for the third, call it with @var{data}.
146 @deffn {Scheme Procedure} call-with-unblocked-asyncs proc
147 @deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
148 @deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
149 @findex scm_c_call_with_unblocked_asyncs
150 Call @var{proc} and unblock the execution of system asyncs by one
151 level for the current thread while it is running. Return the value
152 returned by @var{proc}. For the first two variants, call @var{proc}
153 with no arguments; for the third, call it with @var{data}.
156 @deftypefn {C Function} void scm_frame_block_asyncs ()
157 This function must be used inside a pair of calls to
158 @code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
159 During the dynamic extent of the frame, asyncs are blocked by one level.
162 @deftypefn {C Function} void scm_frame_unblock_asyncs ()
163 This function must be used inside a pair of calls to
164 @code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
165 During the dynamic extent of the frame, asyncs are unblocked by one
170 @subsubsection User asyncs
172 A user async is a pair of a thunk (a parameterless procedure) and a
173 mark. Setting the mark on a user async will cause the thunk to be
174 executed when the user async is passed to @code{run-asyncs}. Setting
175 the mark more than once is satisfied by one execution of the thunk.
177 User asyncs are created with @code{async}. They are marked with
180 @deffn {Scheme Procedure} async thunk
181 @deffnx {C Function} scm_async (thunk)
182 Create a new user async for the procedure @var{thunk}.
185 @deffn {Scheme Procedure} async-mark a
186 @deffnx {C Function} scm_async_mark (a)
187 Mark the user async @var{a} for future execution.
190 @deffn {Scheme Procedure} run-asyncs list_of_a
191 @deffnx {C Function} scm_run_asyncs (list_of_a)
192 Execute all thunks from the marked asyncs of the list @var{list_of_a}.
197 @subsection Dynamic Roots
198 @cindex dynamic roots
200 A @dfn{dynamic root} is a root frame of Scheme evaluation.
201 The top-level repl, for example, is an instance of a dynamic root.
203 Each dynamic root has its own chain of dynamic-wind information. Each
204 has its own set of continuations, jump-buffers, and pending CATCH
205 statements which are inaccessible from the dynamic scope of any
208 In a thread-based system, each thread has its own dynamic root. Therefore,
209 continuations created by one thread may not be invoked by another.
211 Even in a single-threaded system, it is sometimes useful to create a new
212 dynamic root. For example, if you want to apply a procedure, but to
213 not allow that procedure to capture the current continuation, calling
214 the procedure under a new dynamic root will do the job.
216 @deffn {Scheme Procedure} call-with-dynamic-root thunk handler
217 @deffnx {C Function} scm_call_with_dynamic_root (thunk, handler)
218 Evaluate @code{(thunk)} in a new dynamic context, returning its value.
220 If an error occurs during evaluation, apply @var{handler} to the
221 arguments to the throw, just as @code{throw} would. If this happens,
222 @var{handler} is called outside the scope of the new root -- it is
223 called in the same dynamic context in which
224 @code{call-with-dynamic-root} was evaluated.
226 If @var{thunk} captures a continuation, the continuation is rooted at
227 the call to @var{thunk}. In particular, the call to
228 @code{call-with-dynamic-root} is not captured. Therefore,
229 @code{call-with-dynamic-root} always returns at most one time.
231 Before calling @var{thunk}, the dynamic-wind chain is un-wound back to
232 the root and a new chain started for @var{thunk}. Therefore, this call
233 may not do what you expect:
236 ;; Almost certainly a bug:
241 (call-with-dynamic-root
245 (lambda (errcode) errcode))))
248 The problem is, on what port will @samp{fnord} be displayed? You
249 might expect that because of the @code{with-output-to-port} that
250 it will be displayed on the port bound to @code{some-port}. But it
251 probably won't -- before evaluating the thunk, dynamic winds are
252 unwound, including those created by @code{with-output-to-port}.
253 So, the standard output port will have been re-set to its default value
254 before @code{display} is evaluated.
256 (This function was added to Guile mostly to help calls to functions in C
257 libraries that can not tolerate non-local exits or calls that return
258 multiple times. If such functions call back to the interpreter, it should
259 be under a new dynamic root.)
263 @deffn {Scheme Procedure} dynamic-root
264 @deffnx {C Function} scm_dynamic_root ()
265 Return an object representing the current dynamic root.
267 These objects are only useful for comparison using @code{eq?}.
268 They are currently represented as numbers, but your code should
269 in no way depend on this.
272 @c begin (scm-doc-string "boot-9.scm" "quit")
273 @deffn {Scheme Procedure} quit [exit_val]
274 Throw back to the error handler of the current dynamic root.
276 If integer @var{exit_val} is specified and if Guile is being used
277 stand-alone and if quit is called from the initial dynamic-root,
278 @var{exit_val} becomes the exit status of the Guile process and the
282 When Guile is run interactively, errors are caught from within the
283 read-eval-print loop. An error message will be printed and @code{abort}
284 called. A default set of signal handlers is installed, e.g., to allow
285 user interrupt of the interpreter.
287 It is possible to switch to a "batch mode", in which the interpreter
288 will terminate after an error and in which all signals cause their
289 default actions. Switching to batch mode causes any handlers installed
290 from Scheme code to be removed. An example of where this is useful is
291 after forking a new process intended to run non-interactively.
293 @c begin (scm-doc-string "boot-9.scm" "batch-mode?")
294 @deffn {Scheme Procedure} batch-mode?
295 Returns a boolean indicating whether the interpreter is in batch mode.
298 @c begin (scm-doc-string "boot-9.scm" "set-batch-mode?!")
299 @deffn {Scheme Procedure} set-batch-mode?! arg
300 If @var{arg} is true, switches the interpreter to batch mode.
301 The @code{#f} case has not been implemented.
307 @cindex Guile threads
308 @cindex POSIX threads
310 Guile threads are implemented using POSIX threads, they run
311 pre-emptively and concurrently through both Scheme code and system
312 calls. The only exception is for garbage collection, where all
313 threads must rendezvous.
316 * Low level thread primitives::
317 * Higher level thread procedures::
318 * C level thread interface::
322 @node Low level thread primitives
323 @subsubsection Low level thread primitives
325 @c NJFIXME no current mechanism for making sure that these docstrings
328 @c begin (texi-doc-string "guile" "call-with-new-thread")
329 @deffn {Scheme Procedure} call-with-new-thread thunk error-handler
330 Evaluate @code{(thunk)} in a new thread, and new dynamic context,
331 returning a new thread object representing the thread.
333 If an error occurs during evaluation, call error-handler, passing it
334 an error code. If this happens, the error-handler is called outside
335 the scope of the new root -- it is called in the same dynamic context
336 in which with-new-thread was evaluated, but not in the caller's
339 All the evaluation rules for dynamic roots apply to threads.
342 @c begin (texi-doc-string "guile" "join-thread")
343 @deffn {Scheme Procedure} join-thread thread
344 Suspend execution of the calling thread until the target @var{thread}
345 terminates, unless the target @var{thread} has already terminated.
348 @c begin (texi-doc-string "guile" "yield")
349 @deffn {Scheme Procedure} yield
350 If one or more threads are waiting to execute, calling yield forces an
351 immediate context switch to one of them. Otherwise, yield has no effect.
354 @c begin (texi-doc-string "guile" "make-mutex")
355 @deffn {Scheme Procedure} make-mutex
356 Create a new mutex object.
359 @c begin (texi-doc-string "guile" "lock-mutex")
360 @deffn {Scheme Procedure} lock-mutex mutex
361 Lock @var{mutex}. If the mutex is already locked, the calling thread
362 blocks until the mutex becomes available. The function returns when
363 the calling thread owns the lock on @var{mutex}. Locking a mutex that
364 a thread already owns will succeed right away and will not block the
365 thread. That is, Guile's mutexes are @emph{recursive}.
367 When a system async is activated for a thread that is blocked in a
368 call to @code{lock-mutex}, the waiting is interrupted and the async is
369 executed. When the async returns, the waiting is resumed.
372 @deffn {Scheme Procedure} try-mutex mutex
373 Try to lock @var{mutex}. If the mutex is already locked by someone
374 else, return @code{#f}. Else lock the mutex and return @code{#t}.
377 @c begin (texi-doc-string "guile" "unlock-mutex")
378 @deffn {Scheme Procedure} unlock-mutex mutex
379 Unlocks @var{mutex} if the calling thread owns the lock on
380 @var{mutex}. Calling unlock-mutex on a mutex not owned by the current
381 thread results in undefined behaviour. Once a mutex has been unlocked,
382 one thread blocked on @var{mutex} is awakened and grabs the mutex
383 lock. Every call to @code{lock-mutex} by this thread must be matched
384 with a call to @code{unlock-mutex}. Only the last call to
385 @code{unlock-mutex} will actually unlock the mutex.
388 @c begin (texi-doc-string "guile" "make-condition-variable")
389 @deffn {Scheme Procedure} make-condition-variable
390 Make a new condition variable.
393 @c begin (texi-doc-string "guile" "wait-condition-variable")
394 @deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time]
395 Wait until @var{cond-var} has been signalled. While waiting,
396 @var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
397 is locked again when this function returns. When @var{time} is given,
398 it specifies a point in time where the waiting should be aborted. It
399 can be either a integer as returned by @code{current-time} or a pair
400 as returned by @code{gettimeofday}. When the waiting is aborted,
401 @code{#f} is returned. When the condition variable has in fact been
402 signalled, @code{#t} is returned. The mutex is re-locked in any case
403 before @code{wait-condition-variable} returns.
405 When a system async is activated for a thread that is blocked in a
406 call to @code{wait-condition-variable}, the waiting is interrupted,
407 the mutex is locked, and the async is executed. When the async
408 returns, the mutex is unlocked again and the waiting is resumed.
411 @c begin (texi-doc-string "guile" "signal-condition-variable")
412 @deffn {Scheme Procedure} signal-condition-variable cond-var
413 Wake up one thread that is waiting for @var{cv}.
416 @c begin (texi-doc-string "guile" "broadcast-condition-variable")
417 @deffn {Scheme Procedure} broadcast-condition-variable cond-var
418 Wake up all threads that are waiting for @var{cv}.
421 @node Higher level thread procedures
422 @subsubsection Higher level thread procedures
424 @c new by ttn, needs review
426 Higher level thread procedures are available by loading the
427 @code{(ice-9 threads)} module. These provide standardized
428 thread creation and mutex interaction.
430 @deffn macro make-thread proc [args@dots{}]
431 Apply @var{proc} to @var{args} 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.
436 @deffn macro begin-thread first [rest@dots{}]
437 Evaluate forms @var{first} and @var{rest} in a new thread formed by
438 @code{call-with-new-thread} using a default error handler that display
439 the error to the current error port.
442 @deffn macro with-mutex m [body@dots{}]
443 Lock mutex @var{m}, evaluate @var{body}, and then unlock @var{m}.
444 These sub-operations form the branches of a @code{dynamic-wind}.
447 @deffn macro monitor body@dots{}
448 Evaluate @var{body}, with a mutex locked so only one thread can
449 execute that code at any one time. Each @code{monitor} form has its
450 own private mutex and the locking is done as per @code{with-mutex}
451 above. The return value is the return from the last form in
454 The term ``monitor'' comes from operating system theory, where it
455 means a particular bit of code managing access to some resource and
456 which only ever executes on behalf of one process at any one time.
459 @node C level thread interface
460 @subsubsection C level thread interface
462 You can create and manage threads, mutexes, and condition variables
463 with the C versions of the primitives above. For example, you can
464 create a mutex with @code{scm_make_mutex} and lock it with
465 @code{scm_lock_mutex}. In addition to these primitives there is also
466 a second set of primitives for threading related things. These
467 functions and data types are only available from C and can not be
468 mixed with the first set from above. However, they might be more
469 efficient and can be used in situations where Scheme data types are
470 not allowed or are inconvenient to use.
472 Furthermore, they are the primitives that Guile relies on for its own
473 higher level threads. By reimplementing them, you can adapt Guile to
474 different low-level thread implementations.
476 C code in a thread must call a libguile function periodically. When
477 one thread finds garbage collection is required, it waits for all
478 threads to rendezvous before doing that GC. Such a rendezvous is
479 checked within libguile functions. If C code wants to sleep or block
480 in a thread it should use one of the libguile functions provided.
482 Only threads created by Guile can use the libguile functions. Threads
483 created directly with say @code{pthread_create} are unknown to Guile
484 and they cannot call libguile. The stack in such foreign threads is
485 not scanned during GC, so @code{SCM} values generally cannot be held
490 @c Describe SCM_TICK which can be called if no other libguile
491 @c function is being used by a C function.
493 @c Describe "Guile mode", which a thread can enter and exit. There
494 @c are no functions for doing this yet.
496 @c When in guile mode a thread can call libguile, is subject to the
497 @c tick rule, and its stack is scanned. When not in guile mode it
498 @c cannot call libguile, it doesn't have to tick, and its stack is
499 @c not scanned. The strange guile control flow things like
500 @c exceptions, continuations and asyncs only occur when in guile
503 @c When guile mode is exited, the portion of the stack allocated
504 @c while it was in guile mode is still scanned. This portion may not
505 @c be modified when outside guile mode. The stack ends up
506 @c partitioned into alternating guile and non-guile regions.
508 @c Leaving guile mode is convenient when running an extended
509 @c calculation not involving guile, since one doesn't need to worry
510 @c about SCM_TICK calls.
513 @deftp {C Data Type} scm_t_thread
514 This data type represents a thread, to be used with scm_thread_create,
518 @deftypefn {C Function} int scm_thread_create (scm_t_thread *t, void (*proc)(void *), void *data)
519 Create a new thread that will start by calling @var{proc}, passing it
520 @var{data}. A handle for the new thread is stored in @var{t}, which
521 must be non-NULL. The thread terminated when @var{proc} returns.
522 When the thread has not been detached, its handle remains valid after
523 is has terminated so that it can be used with @var{scm_thread_join},
524 for example. When it has been detached, the handle becomes invalid as
525 soon as the thread terminates.
528 @deftypefn {C Function} void scm_thread_detach (scm_t_thread t)
529 Detach the thread @var{t}. See @code{scm_thread_create}.
532 @deftypefn {C Function} void scm_thread_join (scm_t_thread t)
533 Wait for thread @var{t} to terminate. The thread must not have been
534 detached at the time that @code{scm_thread_join} is called, but it
535 might have been detached by the time it terminates.
538 @deftypefn {C Function} scm_t_thread scm_thread_self ()
539 Return the handle of the calling thread.
542 @deftp {C Data Type} scm_t_mutex
543 This data type represents a mutex, to be used with scm_mutex_init,
547 @deftypefn {C Function} void scm_mutex_init (scm_t_mutex *m)
548 Initialize the mutex structure pointed to by @var{m}.
551 @deftypefn {C Function} void scm_mutex_destroy (scm_t_mutex *m)
552 Deallocate all resources associated with @var{m}.
555 @deftypefn {C Function} void scm_mutex_lock (scm_t_mutex *m)
556 Lock the mutex @var{m}. When it is already locked by a different
557 thread, wait until it becomes available. Locking a mutex that is
558 already locked by the current threads is not allowd and results in
559 undefined behavior. The mutices are not guaranteed to be fair. That
560 is, a thread that attempts a lock after yourself might be granted it
564 @deftypefn {C Function} int scm_mutex_trylock (scm_t_mutex *m)
565 Lock @var{m} as with @code{scm_mutex_lock} but don't wait when this
566 does succeed immediately. Returns non-zero when the mutex could in
567 fact be locked , and zero when it is already locked by some other
571 @deftypefn {C Function} void scm_mutex_unlock (scm_t_mutex *m)
572 Unlock the mutex @var{m}. The mutex must have been locked by the
573 current thread, else the behavior is undefined.
576 @deftp {C Data Type} scm_t_cond
577 This data type represents a condition variable, to be used with
581 @deftypefn {C Function} void scm_cond_init (scm_t_cond *c)
582 Initialize the mutex structure pointed to by @var{c}.
585 @deftypefn {C Function} void scm_cond_destroy (scm_t_cond *c)
586 Deallocate all resources associated with @var{c}.
589 @deftypefn {C Function} void scm_cond_wait (scm_t_cond *c, scm_t_mutex *m)
590 Wait for @var{c} to be signalled. While waiting @var{m} is unlocked
591 and locked again before @code{scm_cond_wait} returns.
594 @deftypefn {C Function} void scm_cond_timedwait (scm_t_cond *c, scm_t_mutex *m, timespec *abstime)
595 Wait for @var{c} to be signalled as with @code{scm_cond_wait} but
596 don't wait longer than the point in time specified by @var{abstime}.
597 when the waiting is aborted, zero is returned; non-zero else.
600 @deftypefn {C Function} void scm_cond_signal (scm_t_cond *c)
601 Signal the condition variable @var{c}. When one or more threads are
602 waiting for it to be signalled, select one arbitrarily and let its
606 @deftypefn {C Function} void scm_cond_broadcast (scm_t_cond *c)
607 Signal the condition variable @var{c}. When there are threads waiting
608 for it to be signalled, wake them all up and make all their waits
612 @deftp {C Type} scm_t_key
613 This type represents a key for a thread-specific value.
616 @deftypefn {C Function} void scm_key_create (scm_t_key *keyp)
617 Create a new key for a thread-specific value. Each thread has its own
618 value associated to such a handle. The new handle is stored into
619 @var{keyp}, which must be non-NULL.
622 @deftypefn {C Function} void scm_key_delete (scm_t_key key)
623 This function makes @var{key} invalid as a key for thread-specific data.
626 @deftypefn {C Function} void scm_key_setspecific (scm_t_key key, const void *value)
627 Associate @var{value} with @var{key} in the calling thread.
630 @deftypefn {C Function} int scm_key_getspecific (scm_t_key key)
631 Return the value currently associated with @var{key} in the calling
632 thread. When @code{scm_key_setspecific} has not yet been called in
633 this thread with this key, @code{NULL} is returned.
636 @deftypefn {C Function} int scm_thread_select (...)
637 This function does the same thing as the system's @code{select}
638 function, but in a way that is friendly to the thread implementation.
639 You should call it in preference to the system @code{select}.
647 Fluids are objects to store values in. They have a few properties
648 which make them useful in certain situations: Fluids can have one
649 value per dynamic root (@pxref{Dynamic Roots}), so that changes to the
650 value in a fluid are only visible in the same dynamic root. Since
651 threads are executed in separate dynamic roots, fluids can be used for
652 thread local storage (@pxref{Threads}).
654 Fluids can be used to simulate the desirable effects of dynamically
655 scoped variables. Dynamically scoped variables are useful when you
656 want to set a variable to a value during some dynamic extent in the
657 execution of your program and have them revert to their original value
658 when the control flow is outside of this dynamic extent. See the
659 description of @code{with-fluids} below for details.
661 New fluids are created with @code{make-fluid} and @code{fluid?} is
662 used for testing whether an object is actually a fluid. The values
663 stored in a fluid can be accessed with @code{fluid-ref} and
666 @deffn {Scheme Procedure} make-fluid
667 @deffnx {C Function} scm_make_fluid ()
668 Return a newly created fluid.
669 Fluids are objects of a certain type (a smob) that can hold one SCM
670 value per dynamic root. That is, modifications to this value are
671 only visible to code that executes within the same dynamic root as
672 the modifying code. When a new dynamic root is constructed, it
673 inherits the values from its parent. Because each thread executes
674 in its own dynamic root, you can use fluids for thread local storage.
677 @deffn {Scheme Procedure} fluid? obj
678 @deffnx {C Function} scm_fluid_p (obj)
679 Return @code{#t} iff @var{obj} is a fluid; otherwise, return
683 @deffn {Scheme Procedure} fluid-ref fluid
684 @deffnx {C Function} scm_fluid_ref (fluid)
685 Return the value associated with @var{fluid} in the current
686 dynamic root. If @var{fluid} has not been set, then return
690 @deffn {Scheme Procedure} fluid-set! fluid value
691 @deffnx {C Function} scm_fluid_set_x (fluid, value)
692 Set the value associated with @var{fluid} in the current dynamic root.
695 @code{with-fluids*} temporarily changes the values of one or more fluids,
696 so that the given procedure and each procedure called by it access the
697 given values. After the procedure returns, the old values are restored.
699 @deffn {Scheme Procedure} with-fluids* fluids values thunk
700 @deffnx {C Function} scm_with_fluids (fluids, values, thunk)
701 Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
702 @var{fluids} must be a list of fluids and @var{values} must be the
703 same number of their values to be applied. Each substitution is done
704 in the order given. @var{thunk} must be a procedure with no argument.
705 it is called inside a @code{dynamic-wind} and the fluids are
706 set/restored when control enter or leaves the established dynamic
710 @deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
711 Execute @var{body...} while each @var{fluid} is set to the
712 corresponding @var{value}. Both @var{fluid} and @var{value} are
713 evaluated and @var{fluid} must yield a fluid. @var{body...} is
714 executed inside a @code{dynamic-wind} and the fluids are set/restored
715 when control enter or leaves the established dynamic extent.
718 @deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
719 @deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
720 The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
721 except that it takes a C function to call instead of a Scheme thunk.
723 The function @code{scm_c_with_fluid} is similar but only allows one
724 fluid to be set instead of a list.
727 @deftypefn {C Function} void scm_frame_fluid (SCM fluid, SCM val)
728 This function must be used inside a pair of calls to
729 @code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
730 During the dynamic extent of the frame, the fluid @var{fluid} is set
733 More precisely, the value of the fluid is swapped with a `backup'
734 value whenever the frame is entered or left. The backup value is
735 initialized with the @var{val} argument.
742 Futures are a convenient way to run a calculation in a new thread, and
743 only wait for the result when it's actually needed.
745 Futures are similar to promises (@pxref{Delayed Evaluation}), in that
746 they allow mainline code to continue immediately. But @code{delay}
747 doesn't evaluate at all until forced, whereas @code{future} starts
748 immediately in a new thread.
750 @deffn {syntax} future expr
751 Begin evaluating @var{expr} in a new thread, and return a ``future''
752 object representing the calculation.
755 @deffn {Scheme Procedure} make-future thunk
756 @deffnx {C Function} scm_make_future (thunk)
757 Begin evaluating the call @code{(@var{thunk})} in a new thread, and
758 return a ``future'' object representing the calculation.
761 @deffn {Scheme Procedure} future-ref f
762 @deffnx {C Function} scm_future_ref (f)
763 Return the value computed by the future @var{f}. If @var{f} has not
764 yet finished executing then wait for it to do so.
769 @subsection Parallel forms
770 @cindex parallel forms
772 The functions described in this section are available from
775 (use-modules (ice-9 threads))
778 @deffn syntax parallel expr1 @dots{} exprN
779 Evaluate each @var{expr} expression in parallel, each in a new thread.
780 Return the results as a set of @var{N} multiple values
781 (@pxref{Multiple Values}).
784 @deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
785 Evaluate each @var{expr} in parallel, each in a new thread, then bind
786 the results to the corresponding @var{var} variables and evaluate
789 @code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
790 expressions for the bindings are evaluated in parallel.
793 @deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
794 @deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
795 Call @var{proc} on the elements of the given lists. @code{par-map}
796 returns a list comprising the return values from @var{proc}.
797 @code{par-for-each} returns an unspecified value, but waits for all
800 The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
801 @var{elemN})}, where each @var{elem} is from the corresponding
802 @var{lst}. Each @var{lst} must be the same length. The calls are
803 made in parallel, each in a new thread.
805 These functions are like @code{map} and @code{for-each} (@pxref{List
806 Mapping}), but make their @var{proc} calls in parallel.
809 @deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
810 @deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
811 Call @var{proc} on the elements of the given lists, in the same way as
812 @code{par-map} and @code{par-for-each} above, but use no more than
813 @var{n} new threads at any one time. The order in which calls are
814 initiated within that threads limit is unspecified.
816 These functions are good for controlling resource consumption if
817 @var{proc} calls might be costly, or if there are many to be made. On
818 a dual-CPU system for instance @math{@var{n}=4} might be enough to
819 keep the CPUs utilized, and not consume too much memory.
822 @deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
823 Apply @var{pproc} to the elements of the given lists, and apply
824 @var{sproc} to each result returned by @var{pproc}. The final return
825 value is unspecified, but all calls will have been completed before
828 The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
829 @var{elemN}))}, where each @var{elem} is from the corresponding
830 @var{lst}. Each @var{lst} must have the same number of elements.
832 The @var{pproc} calls are made in parallel, in new threads. No more
833 than @var{n} new threads are used at any one time. The order in which
834 @var{pproc} calls are initiated within that limit is unspecified.
836 The @var{sproc} calls are made serially, in list element order, one at
837 a time. @var{pproc} calls on later elements may execute in parallel
838 with the @var{sproc} calls. Exactly which thread makes each
839 @var{sproc} call is unspecified.
841 This function is designed for individual calculations that can be done
842 in parallel, but with results needing to be handled serially, for
843 instance to write them to a file. The @var{n} limit on threads
844 controls system resource usage when there are many calculations or
845 when they might be costly.
847 It will be seen that @code{n-for-each-par-map} is like a combination
848 of @code{n-par-map} and @code{for-each},
851 (for-each sproc (n-par-map pproc lst1 ... lstN))
855 But the actual implementation is more efficient since each @var{sproc}
856 call, in turn, can be initiated once the relevant @var{pproc} call has
857 completed, it doesn't need to wait for all to finish.
862 @c TeX-master: "guile.texi"