Fix type-checking for the second argument of `eval'.
[bpt/guile.git] / doc / ref / api-scheduling.texi
CommitLineData
07d83abe
MV
1@c -*-texinfo-*-
2@c This is part of the GNU Guile Reference Manual.
07e02175 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
7@page
8@node Scheduling
9@section Threads, Mutexes, Asyncs and Dynamic Roots
10
11[FIXME: This is pasted in from Tom Lord's original guile.texi chapter
12plus the Cygnus programmer's manual; it should be *very* carefully
13reviewed and largely reorganized.]
14
15@menu
16* Arbiters:: Synchronization primitives.
17* Asyncs:: Asynchronous procedure invocation.
b4fddbbe 18* Continuation Barriers:: Protection from non-local control flow.
07d83abe 19* Threads:: Multiple threads of execution.
2567692a 20* Mutexes and Condition Variables:: Synchronization primitives.
b4fddbbe 21* Blocking:: How to block properly in guile mode.
2567692a 22* Critical Sections:: Avoiding concurrency and reentries.
b4fddbbe 23* Fluids and Dynamic States:: Thread-local variables, etc.
07d83abe
MV
24* Parallel Forms:: Parallel execution of forms.
25@end menu
26
27
28@node Arbiters
29@subsection Arbiters
07d83abe
MV
30@cindex arbiters
31
e136aab0
KR
32Arbiters are synchronization objects, they can be used by threads to
33control access to a shared resource. An arbiter can be locked to
34indicate a resource is in use, and unlocked when done.
07d83abe 35
b4fddbbe
MV
36An arbiter is like a light-weight mutex (@pxref{Mutexes and Condition
37Variables}). It uses less memory and may be faster, but there's no
38way for a thread to block waiting on an arbiter, it can only test and
39get the status returned.
07d83abe
MV
40
41@deffn {Scheme Procedure} make-arbiter name
42@deffnx {C Function} scm_make_arbiter (name)
cdf1ad3b
MV
43Return an object of type arbiter and name @var{name}. Its
44state is initially unlocked. Arbiters are a way to achieve
45process synchronization.
07d83abe
MV
46@end deffn
47
48@deffn {Scheme Procedure} try-arbiter arb
49@deffnx {C Function} scm_try_arbiter (arb)
cdf1ad3b
MV
50@deffnx {C Function} scm_try_arbiter (arb)
51If @var{arb} is unlocked, then lock it and return @code{#t}.
52If @var{arb} is already locked, then do nothing and return
53@code{#f}.
07d83abe
MV
54@end deffn
55
56@deffn {Scheme Procedure} release-arbiter arb
57@deffnx {C Function} scm_release_arbiter (arb)
e136aab0
KR
58If @var{arb} is locked, then unlock it and return @code{#t}. If
59@var{arb} is already unlocked, then do nothing and return @code{#f}.
60
61Typical usage is for the thread which locked an arbiter to later
62release it, but that's not required, any thread can release it.
07d83abe
MV
63@end deffn
64
65
66@node Asyncs
67@subsection Asyncs
68
69@cindex asyncs
70@cindex user asyncs
71@cindex system asyncs
72
73Asyncs are a means of deferring the excution of Scheme code until it is
74safe to do so.
75
76Guile provides two kinds of asyncs that share the basic concept but are
77otherwise quite different: system asyncs and user asyncs. System asyncs
78are integrated into the core of Guile and are executed automatically
79when the system is in a state to allow the execution of Scheme code.
80For example, it is not possible to execute Scheme code in a POSIX signal
81handler, but such a signal handler can queue a system async to be
82executed in the near future, when it is safe to do so.
83
84System asyncs can also be queued for threads other than the current one.
85This way, you can cause threads to asynchronously execute arbitrary
86code.
87
88User asyncs offer a convenient means of queueing procedures for future
89execution and triggering this execution. They will not be executed
90automatically.
91
92@menu
93* System asyncs::
94* User asyncs::
95@end menu
96
97@node System asyncs
98@subsubsection System asyncs
99
100To cause the future asynchronous execution of a procedure in a given
101thread, use @code{system-async-mark}.
102
103Automatic invocation of system asyncs can be temporarily disabled by
104calling @code{call-with-blocked-asyncs}. This function works by
105temporarily increasing the @emph{async blocking level} of the current
106thread while a given procedure is running. The blocking level starts
107out at zero, and whenever a safe point is reached, a blocking level
108greater than zero will prevent the execution of queued asyncs.
109
110Analogously, the procedure @code{call-with-unblocked-asyncs} will
111temporarily decrease the blocking level of the current thread. You
112can use it when you want to disable asyncs by default and only allow
113them temporarily.
114
115In addition to the C versions of @code{call-with-blocked-asyncs} and
116@code{call-with-unblocked-asyncs}, C code can use
661ae7ab
MV
117@code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
118inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
119unblock system asyncs temporarily.
07d83abe
MV
120
121@deffn {Scheme Procedure} system-async-mark proc [thread]
122@deffnx {C Function} scm_system_async_mark (proc)
123@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
124Mark @var{proc} (a procedure with zero arguments) for future execution
125in @var{thread}. When @var{proc} has already been marked for
126@var{thread} but has not been executed yet, this call has no effect.
127When @var{thread} is omitted, the thread that called
128@code{system-async-mark} is used.
129
130This procedure is not safe to be called from signal handlers. Use
131@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
132signal handlers.
133@end deffn
134
135@c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
136@c scm_c_call_with_unblocked_asyncs puts "void" into the function
137@c index. Would prefer to use @deftypefnx if makeinfo allowed that,
138@c or a @deftypefn with an empty return type argument if it didn't
139@c introduce an extra space.
140
141@deffn {Scheme Procedure} call-with-blocked-asyncs proc
142@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
1b09b607 143@deffnx {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
07d83abe
MV
144@findex scm_c_call_with_blocked_asyncs
145Call @var{proc} and block the execution of system asyncs by one level
146for the current thread while it is running. Return the value returned
147by @var{proc}. For the first two variants, call @var{proc} with no
148arguments; for the third, call it with @var{data}.
149@end deffn
150
151@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
152@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
1b09b607 153@deffnx {C Function} {void *} scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
07d83abe
MV
154@findex scm_c_call_with_unblocked_asyncs
155Call @var{proc} and unblock the execution of system asyncs by one
156level for the current thread while it is running. Return the value
157returned by @var{proc}. For the first two variants, call @var{proc}
158with no arguments; for the third, call it with @var{data}.
159@end deffn
160
661ae7ab 161@deftypefn {C Function} void scm_dynwind_block_asyncs ()
07d83abe 162This function must be used inside a pair of calls to
661ae7ab
MV
163@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
164Wind}). During the dynwind context, asyncs are blocked by one level.
07d83abe
MV
165@end deftypefn
166
661ae7ab 167@deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
07d83abe 168This function must be used inside a pair of calls to
661ae7ab
MV
169@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
170Wind}). During the dynwind context, asyncs are unblocked by one
07d83abe
MV
171level.
172@end deftypefn
173
174@node User asyncs
175@subsubsection User asyncs
176
177A user async is a pair of a thunk (a parameterless procedure) and a
178mark. Setting the mark on a user async will cause the thunk to be
179executed when the user async is passed to @code{run-asyncs}. Setting
180the mark more than once is satisfied by one execution of the thunk.
181
182User asyncs are created with @code{async}. They are marked with
183@code{async-mark}.
184
185@deffn {Scheme Procedure} async thunk
186@deffnx {C Function} scm_async (thunk)
187Create a new user async for the procedure @var{thunk}.
188@end deffn
189
190@deffn {Scheme Procedure} async-mark a
191@deffnx {C Function} scm_async_mark (a)
192Mark the user async @var{a} for future execution.
193@end deffn
194
195@deffn {Scheme Procedure} run-asyncs list_of_a
196@deffnx {C Function} scm_run_asyncs (list_of_a)
197Execute all thunks from the marked asyncs of the list @var{list_of_a}.
198@end deffn
199
b4fddbbe
MV
200@node Continuation Barriers
201@subsection Continuation Barriers
07d83abe 202
b4fddbbe
MV
203The non-local flow of control caused by continuations might sometimes
204not be wanted. You can use @code{with-continuation-barrier} etc to
205errect fences that continuations can not pass.
07d83abe 206
673ba2da 207@deffn {Scheme Procedure} with-continuation-barrier proc
b4fddbbe
MV
208@deffnx {C Function} scm_with_continuation_barrier (proc)
209Call @var{proc} and return its result. Do not allow the invocation of
210continuations that would leave or enter the dynamic extent of the call
211to @code{with-continuation-barrier}. Such an attempt causes an error
212to be signaled.
07d83abe 213
b4fddbbe
MV
214Throws (such as errors) that are not caught from within @var{proc} are
215caught by @code{with-continuation-barrier}. In that case, a short
216message is printed to the current error port and @code{#f} is returned.
07d83abe 217
b4fddbbe 218Thus, @code{with-continuation-barrier} returns exactly once.
07d83abe
MV
219@end deffn
220
c2110081 221@deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
b4fddbbe
MV
222Like @code{scm_with_continuation_barrier} but call @var{func} on
223@var{data}. When an error is caught, @code{NULL} is returned.
224@end deftypefn
07d83abe
MV
225
226@node Threads
227@subsection Threads
228@cindex threads
229@cindex Guile threads
230@cindex POSIX threads
231
cdf1ad3b
MV
232@deffn {Scheme Procedure} all-threads
233@deffnx {C Function} scm_all_threads ()
234Return a list of all threads.
235@end deffn
236
237@deffn {Scheme Procedure} current-thread
238@deffnx {C Function} scm_current_thread ()
239Return the thread that called this function.
240@end deffn
07d83abe
MV
241
242@c begin (texi-doc-string "guile" "call-with-new-thread")
23f2b9a3 243@deffn {Scheme Procedure} call-with-new-thread thunk [handler]
b4fddbbe
MV
244Call @code{thunk} in a new thread and with a new dynamic state,
245returning the new thread. The procedure @var{thunk} is called via
246@code{with-continuation-barrier}.
07d83abe 247
b4fddbbe
MV
248When @var{handler} is specified, then @var{thunk} is called from
249within a @code{catch} with tag @code{#t} that has @var{handler} as its
250handler. This catch is established inside the continuation barrier.
07d83abe 251
b4fddbbe
MV
252Once @var{thunk} or @var{handler} returns, the return value is made
253the @emph{exit value} of the thread and the thread is terminated.
07d83abe
MV
254@end deffn
255
b4fddbbe
MV
256@deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
257Call @var{body} in a new thread, passing it @var{body_data}, returning
258the new thread. The function @var{body} is called via
259@code{scm_c_with_continuation_barrier}.
260
261When @var{handler} is non-@code{NULL}, @var{body} is called via
262@code{scm_internal_catch} with tag @code{SCM_BOOL_T} that has
263@var{handler} and @var{handler_data} as the handler and its data. This
264catch is established inside the continuation barrier.
265
266Once @var{body} or @var{handler} returns, the return value is made the
267@emph{exit value} of the thread and the thread is terminated.
268@end deftypefn
269
07d83abe
MV
270@c begin (texi-doc-string "guile" "join-thread")
271@deffn {Scheme Procedure} join-thread thread
300b1ae5 272@deffnx {C Function} scm_join_thread (thread)
b4fddbbe
MV
273Wait for @var{thread} to terminate and return its exit value. Threads
274that have not been created with @code{call-with-new-thread} or
275@code{scm_spawn_thread} have an exit value of @code{#f}.
07d83abe
MV
276@end deffn
277
cdf1ad3b
MV
278@deffn {Scheme Procedure} thread-exited? thread
279@deffnx {C Function} scm_thread_exited_p (thread)
280Return @code{#t} iff @var{thread} has exited.
281@end deffn
282
07d83abe
MV
283@c begin (texi-doc-string "guile" "yield")
284@deffn {Scheme Procedure} yield
285If one or more threads are waiting to execute, calling yield forces an
286immediate context switch to one of them. Otherwise, yield has no effect.
287@end deffn
288
07e02175
LC
289@deffn {Scheme Procedure} cancel-thread thread
290@deffnx {C Function} scm_cancel_thread (thread)
291Asynchronously notify @var{thread} to exit. Immediately after
292receiving this notification, @var{thread} will call its cleanup handler
293(if one has been set) and then terminate, aborting any evaluation that
294is in progress.
295
296Because Guile threads are isomorphic with POSIX threads, @var{thread}
297will not receive its cancellation signal until it reaches a cancellation
298point. See your operating system's POSIX threading documentation for
299more information on cancellation points; note that in Guile, unlike
300native POSIX threads, a thread can receive a cancellation notification
301while attempting to lock a mutex.
302@end deffn
303
304@deffn {Scheme Procedure} set-thread-cleanup! thread proc
305@deffnx {C Function} scm_set_thread_cleanup_x (thread, proc)
306Set @var{proc} as the cleanup handler for the thread @var{thread}.
307@var{proc}, which must be a thunk, will be called when @var{thread}
308exits, either normally or by being canceled. Thread cleanup handlers
309can be used to perform useful tasks like releasing resources, such as
310locked mutexes, when thread exit cannot be predicted.
311
312The return value of @var{proc} will be set as the @emph{exit value} of
313@var{thread}.
314
315To remove a cleanup handler, pass @code{#f} for @var{proc}.
316@end deffn
317
318@deffn {Scheme Procedure} thread-cleanup thread
319@deffnx {C Function} scm_thread_cleanup (thread)
320Return the cleanup handler currently installed for the thread
321@var{thread}. If no cleanup handler is currently installed,
322thread-cleanup returns @code{#f}.
323@end deffn
324
07d83abe
MV
325Higher level thread procedures are available by loading the
326@code{(ice-9 threads)} module. These provide standardized
3cf066df 327thread creation.
07d83abe
MV
328
329@deffn macro make-thread proc [args@dots{}]
330Apply @var{proc} to @var{args} in a new thread formed by
331@code{call-with-new-thread} using a default error handler that display
b4fddbbe
MV
332the error to the current error port. The @var{args@dots{}}
333expressions are evaluated in the new thread.
07d83abe
MV
334@end deffn
335
336@deffn macro begin-thread first [rest@dots{}]
337Evaluate forms @var{first} and @var{rest} in a new thread formed by
338@code{call-with-new-thread} using a default error handler that display
339the error to the current error port.
340@end deffn
341
2567692a
MV
342@node Mutexes and Condition Variables
343@subsection Mutexes and Condition Variables
344@cindex mutex
345@cindex condition variable
346
347A mutex is a thread synchronization object, it can be used by threads
348to control access to a shared resource. A mutex can be locked to
349indicate a resource is in use, and other threads can then block on the
350mutex to wait for the resource (or can just test and do something else
351if not available). ``Mutex'' is short for ``mutual exclusion''.
352
353There are two types of mutexes in Guile, ``standard'' and
354``recursive''. They're created by @code{make-mutex} and
355@code{make-recursive-mutex} respectively, the operation functions are
356then common to both.
357
358Note that for both types of mutex there's no protection against a
359``deadly embrace''. For instance if one thread has locked mutex A and
360is waiting on mutex B, but another thread owns B and is waiting on A,
361then an endless wait will occur (in the current implementation).
362Acquiring requisite mutexes in a fixed order (like always A before B)
363in all threads is one way to avoid such problems.
364
365@sp 1
366@deffn {Scheme Procedure} make-mutex
367@deffnx {C Function} scm_make_mutex ()
368Return a new standard mutex. It is initially unlocked.
369@end deffn
370
371@deffn {Scheme Procedure} make-recursive-mutex
372@deffnx {C Function} scm_make_recursive_mutex ()
373Create a new recursive mutex. It is initialloy unlocked.
374@end deffn
375
376@deffn {Scheme Procedure} lock-mutex mutex
377@deffnx {C Function} scm_lock_mutex (mutex)
378Lock @var{mutex}. If the mutex is already locked by another thread
379then block and return only when @var{mutex} has been acquired.
380
381For standard mutexes (@code{make-mutex}), and error is signalled if
382the thread has itself already locked @var{mutex}.
383
384For a recursive mutex (@code{make-recursive-mutex}), if the thread has
385itself already locked @var{mutex}, then a further @code{lock-mutex}
386call increments the lock count. An additional @code{unlock-mutex}
387will be required to finally release.
388
389When a system async (@pxref{System asyncs}) is activated for a thread
390blocked in @code{lock-mutex}, the wait is interrupted and the async is
391executed. When the async returns, the wait resumes.
392@end deffn
393
661ae7ab
MV
394@deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
395Arrange for @var{mutex} to be locked whenever the current dynwind
396context is entered and to be unlocked when it is exited.
2567692a
MV
397@end deftypefn
398
399@deffn {Scheme Procedure} try-mutex mx
400@deffnx {C Function} scm_try_mutex (mx)
401Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
402be acquired immediately then this is done and the return is @code{#t}.
403If @var{mutex} is locked by some other thread then nothing is done and
404the return is @code{#f}.
405@end deffn
406
407@deffn {Scheme Procedure} unlock-mutex mutex
408@deffnx {C Function} scm_unlock_mutex (mutex)
409Unlock @var{mutex}. An error is signalled if @var{mutex} is not
410locked by the calling thread.
411@end deffn
412
413@deffn {Scheme Procedure} make-condition-variable
414@deffnx {C Function} scm_make_condition_variable ()
415Return a new condition variable.
416@end deffn
417
418@deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
419@deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
420Wait until @var{condvar} has been signalled. While waiting,
421@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
422is locked again when this function returns. When @var{time} is given,
423it specifies a point in time where the waiting should be aborted. It
424can be either a integer as returned by @code{current-time} or a pair
425as returned by @code{gettimeofday}. When the waiting is aborted,
426@code{#f} is returned. When the condition variable has in fact been
427signalled, @code{#t} is returned. The mutex is re-locked in any case
428before @code{wait-condition-variable} returns.
429
430When a system async is activated for a thread that is blocked in a
431call to @code{wait-condition-variable}, the waiting is interrupted,
432the mutex is locked, and the async is executed. When the async
433returns, the mutex is unlocked again and the waiting is resumed. When
434the thread block while re-acquiring the mutex, execution of asyncs is
435blocked.
436@end deffn
437
438@deffn {Scheme Procedure} signal-condition-variable condvar
439@deffnx {C Function} scm_signal_condition_variable (condvar)
440Wake up one thread that is waiting for @var{condvar}.
441@end deffn
442
443@deffn {Scheme Procedure} broadcast-condition-variable condvar
444@deffnx {C Function} scm_broadcast_condition_variable (condvar)
445Wake up all threads that are waiting for @var{condvar}.
446@end deffn
447
448@sp 1
449The following are higher level operations on mutexes. These are
450available from
451
452@example
453(use-modules (ice-9 threads))
454@end example
455
456@deffn macro with-mutex mutex [body@dots{}]
457Lock @var{mutex}, evaluate the @var{body} forms, then unlock
458@var{mutex}. The return value is the return from the last @var{body}
459form.
460
461The lock, body and unlock form the branches of a @code{dynamic-wind}
462(@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
463error or new continuation exits @var{body}, and is re-locked if
464@var{body} is re-entered by a captured continuation.
465@end deffn
466
467@deffn macro monitor body@dots{}
468Evaluate the @var{body} forms, with a mutex locked so only one thread
469can execute that code at any one time. The return value is the return
470from the last @var{body} form.
471
472Each @code{monitor} form has its own private mutex and the locking and
473evaluation is as per @code{with-mutex} above. A standard mutex
474(@code{make-mutex}) is used, which means @var{body} must not
475recursively re-enter the @code{monitor} form.
476
477The term ``monitor'' comes from operating system theory, where it
478means a particular bit of code managing access to some resource and
479which only ever executes on behalf of one process at any one time.
480@end deffn
481
482
b4fddbbe
MV
483@node Blocking
484@subsection Blocking in Guile Mode
07d83abe 485
b4fddbbe
MV
486A thread must not block outside of a libguile function while it is in
487guile mode. The following functions can be used to temporily leave
488guile mode or to perform some common blocking operations in a supported
489way.
07d83abe 490
54428bb8
MV
491@deftypefn {C Function} {void *} scm_without_guile (void *(*func) (void *), void *data)
492Leave guile mode, call @var{func} on @var{data}, enter guile mode and
493return the result of calling @var{func}.
07d83abe 494
b4fddbbe 495While a thread has left guile mode, it must not call any libguile
54428bb8
MV
496functions except @code{scm_with_guile} or @code{scm_without_guile} and
497must not use any libguile macros. Also, local variables of type
498@code{SCM} that are allocated while not in guile mode are not
499protected from the garbage collector.
500
501When used from non-guile mode, calling @code{scm_without_guile} is
502still allowed: it simply calls @var{func}. In that way, you can leave
503guile mode without having to know whether the current thread is in
504guile mode or not.
07d83abe
MV
505@end deftypefn
506
b4fddbbe
MV
507@deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
508Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
509the mutex.
07d83abe
MV
510@end deftypefn
511
b4fddbbe
MV
512@deftypefn {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
513@deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
514Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
515leaves guile mode while waiting for the condition variable.
07d83abe
MV
516@end deftypefn
517
b4fddbbe
MV
518@deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
519Like @code{select} but leaves guile mode while waiting. Also, the
520delivery of a system async causes this function to be interrupted with
521error code @code{EINTR}.
07d83abe
MV
522@end deftypefn
523
b4fddbbe
MV
524@deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
525Like @code{sleep}, but leaves guile mode while sleeping. Also, the
526delivery of a system async causes this function to be interrupted.
07d83abe
MV
527@end deftypefn
528
b4fddbbe
MV
529@deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
530Like @code{usleep}, but leaves guile mode while sleeping. Also, the
531delivery of a system async causes this function to be interrupted.
07d83abe
MV
532@end deftypefn
533
07d83abe 534
2567692a
MV
535@node Critical Sections
536@subsection Critical Sections
537
538@deffn {C Macro} SCM_CRITICAL_SECTION_START
539@deffnx {C Macro} SCM_CRITICAL_SECTION_END
540These two macros can be used to delimit a critical section.
541Syntactically, they are both statements and need to be followed
542immediately by a semicolon.
543
544Executing @code{SCM_CRITICAL_SECTION_START} will lock a recursive
545mutex and block the executing of system asyncs. Executing
546@code{SCM_CRITICAL_SECTION_END} will unblock the execution of system
547asyncs and unlock the mutex. Thus, the code that executes between
548these two macros can only be executed in one thread at any one time
549and no system asyncs will run. However, because the mutex is a
550recursive one, the code might still be reentered by the same thread.
551You must either allow for this or avoid it, both by careful coding.
552
553On the other hand, critical sections delimited with these macros can
554be nested since the mutex is recursive.
555
556You must make sure that for each @code{SCM_CRITICAL_SECTION_START},
557the corresponding @code{SCM_CRITICAL_SECTION_END} is always executed.
558This means that no non-local exit (such as a signalled error) might
559happen, for example.
560@end deffn
561
661ae7ab
MV
562@deftypefn {C Function} void scm_dynwind_critical_section (SCM mutex)
563Call @code{scm_dynwind_lock_mutex} on @var{mutex} and call
564@code{scm_dynwind_block_asyncs}. When @var{mutex} is false, a recursive
2567692a
MV
565mutex provided by Guile is used instead.
566
661ae7ab
MV
567The effect of a call to @code{scm_dynwind_critical_section} is that
568the current dynwind context (@pxref{Dynamic Wind}) turns into a
569critical section. Because of the locked mutex, no second thread can
570enter it concurrently and because of the blocked asyncs, no system
571async can reenter it from the current thread.
2567692a
MV
572
573When the current thread reenters the critical section anyway, the kind
574of @var{mutex} determines what happens: When @var{mutex} is recursive,
575the reentry is allowed. When it is a normal mutex, an error is
576signalled.
577@end deftypefn
578
579
b4fddbbe
MV
580@node Fluids and Dynamic States
581@subsection Fluids and Dynamic States
07d83abe
MV
582
583@cindex fluids
584
b4fddbbe
MV
585A @emph{fluid} is an object that can store one value per @emph{dynamic
586state}. Each thread has a current dynamic state, and when accessing a
587fluid, this current dynamic state is used to provide the actual value.
588In this way, fluids can be used for thread local storage, but they are
589in fact more flexible: dynamic states are objects of their own and can
590be made current for more than one thread at the same time, or only be
591made current temporarily, for example.
592
593Fluids can also be used to simulate the desirable effects of
594dynamically scoped variables. Dynamically scoped variables are useful
595when you want to set a variable to a value during some dynamic extent
596in the execution of your program and have them revert to their
597original value when the control flow is outside of this dynamic
598extent. See the description of @code{with-fluids} below for details.
07d83abe
MV
599
600New fluids are created with @code{make-fluid} and @code{fluid?} is
601used for testing whether an object is actually a fluid. The values
602stored in a fluid can be accessed with @code{fluid-ref} and
603@code{fluid-set!}.
604
605@deffn {Scheme Procedure} make-fluid
606@deffnx {C Function} scm_make_fluid ()
607Return a newly created fluid.
b4fddbbe
MV
608Fluids are objects that can hold one
609value per dynamic state. That is, modifications to this value are
610only visible to code that executes with the same dynamic state as
611the modifying code. When a new dynamic state is constructed, it
612inherits the values from its parent. Because each thread normally executes
613with its own dynamic state, you can use fluids for thread local storage.
07d83abe
MV
614@end deffn
615
616@deffn {Scheme Procedure} fluid? obj
617@deffnx {C Function} scm_fluid_p (obj)
618Return @code{#t} iff @var{obj} is a fluid; otherwise, return
619@code{#f}.
620@end deffn
621
622@deffn {Scheme Procedure} fluid-ref fluid
623@deffnx {C Function} scm_fluid_ref (fluid)
624Return the value associated with @var{fluid} in the current
625dynamic root. If @var{fluid} has not been set, then return
626@code{#f}.
627@end deffn
628
629@deffn {Scheme Procedure} fluid-set! fluid value
630@deffnx {C Function} scm_fluid_set_x (fluid, value)
631Set the value associated with @var{fluid} in the current dynamic root.
632@end deffn
633
634@code{with-fluids*} temporarily changes the values of one or more fluids,
635so that the given procedure and each procedure called by it access the
636given values. After the procedure returns, the old values are restored.
637
cdf1ad3b
MV
638@deffn {Scheme Procedure} with-fluid* fluid value thunk
639@deffnx {C Function} scm_with_fluid (fluid, value, thunk)
640Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
641@var{thunk} must be a procedure with no argument.
642@end deffn
643
07d83abe
MV
644@deffn {Scheme Procedure} with-fluids* fluids values thunk
645@deffnx {C Function} scm_with_fluids (fluids, values, thunk)
646Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
647@var{fluids} must be a list of fluids and @var{values} must be the
648same number of their values to be applied. Each substitution is done
649in the order given. @var{thunk} must be a procedure with no argument.
650it is called inside a @code{dynamic-wind} and the fluids are
651set/restored when control enter or leaves the established dynamic
652extent.
653@end deffn
654
655@deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
656Execute @var{body...} while each @var{fluid} is set to the
657corresponding @var{value}. Both @var{fluid} and @var{value} are
658evaluated and @var{fluid} must yield a fluid. @var{body...} is
659executed inside a @code{dynamic-wind} and the fluids are set/restored
660when control enter or leaves the established dynamic extent.
661@end deffn
662
663@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
664@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
665The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
666except that it takes a C function to call instead of a Scheme thunk.
667
668The function @code{scm_c_with_fluid} is similar but only allows one
669fluid to be set instead of a list.
670@end deftypefn
671
661ae7ab 672@deftypefn {C Function} void scm_dynwind_fluid (SCM fluid, SCM val)
07d83abe 673This function must be used inside a pair of calls to
661ae7ab
MV
674@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
675Wind}). During the dynwind context, the fluid @var{fluid} is set to
676@var{val}.
07d83abe
MV
677
678More precisely, the value of the fluid is swapped with a `backup'
661ae7ab
MV
679value whenever the dynwind context is entered or left. The backup
680value is initialized with the @var{val} argument.
07d83abe
MV
681@end deftypefn
682
b4fddbbe
MV
683@deffn {Scheme Procedure} make-dynamic-state [parent]
684@deffnx {C Function} scm_make_dynamic_state (parent)
685Return a copy of the dynamic state object @var{parent}
686or of the current dynamic state when @var{parent} is omitted.
687@end deffn
688
689@deffn {Scheme Procedure} dynamic-state? obj
690@deffnx {C Function} scm_dynamic_state_p (obj)
691Return @code{#t} if @var{obj} is a dynamic state object;
692return @code{#f} otherwise.
693@end deffn
694
695@deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
696Return non-zero if @var{obj} is a dynamic state object;
697return zero otherwise.
698@end deftypefn
699
700@deffn {Scheme Procedure} current-dynamic-state
701@deffnx {C Function} scm_current_dynamic_state ()
702Return the current dynamic state object.
703@end deffn
704
705@deffn {Scheme Procedure} set-current-dynamic-state state
706@deffnx {C Function} scm_set_current_dynamic_state (state)
707Set the current dynamic state object to @var{state}
708and return the previous current dynamic state object.
709@end deffn
710
711@deffn {Scheme Procedure} with-dynamic-state state proc
712@deffnx {C Function} scm_with_dynamic_state (state, proc)
713Call @var{proc} while @var{state} is the current dynamic
714state object.
715@end deffn
716
661ae7ab
MV
717@deftypefn {C Procedure} void scm_dynwind_current_dynamic_state (SCM state)
718Set the current dynamic state to @var{state} for the current dynwind
719context.
b4fddbbe
MV
720@end deftypefn
721
c2110081 722@deftypefn {C Procedure} {void *} scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
b4fddbbe
MV
723Like @code{scm_with_dynamic_state}, but call @var{func} with
724@var{data}.
725@end deftypefn
726
cc19cda7
MV
727@c @node Futures
728@c @subsection Futures
729@c @cindex futures
730
731@c -- Futures are disabled for the time being, see futures.h for an
732@c -- explanation.
733
734@c Futures are a convenient way to run a calculation in a new thread, and
735@c only wait for the result when it's actually needed.
736
737@c Futures are similar to promises (@pxref{Delayed Evaluation}), in that
738@c they allow mainline code to continue immediately. But @code{delay}
739@c doesn't evaluate at all until forced, whereas @code{future} starts
740@c immediately in a new thread.
741
742@c @deffn {syntax} future expr
743@c Begin evaluating @var{expr} in a new thread, and return a ``future''
744@c object representing the calculation.
745@c @end deffn
746
747@c @deffn {Scheme Procedure} make-future thunk
748@c @deffnx {C Function} scm_make_future (thunk)
749@c Begin evaluating the call @code{(@var{thunk})} in a new thread, and
750@c return a ``future'' object representing the calculation.
751@c @end deffn
752
753@c @deffn {Scheme Procedure} future-ref f
754@c @deffnx {C Function} scm_future_ref (f)
755@c Return the value computed by the future @var{f}. If @var{f} has not
756@c yet finished executing then wait for it to do so.
757@c @end deffn
07d83abe
MV
758
759
760@node Parallel Forms
761@subsection Parallel forms
762@cindex parallel forms
763
764The functions described in this section are available from
765
766@example
767(use-modules (ice-9 threads))
768@end example
769
770@deffn syntax parallel expr1 @dots{} exprN
af1323c5 771Evaluate each @var{expr} expression in parallel, each in its own thread.
07d83abe
MV
772Return the results as a set of @var{N} multiple values
773(@pxref{Multiple Values}).
774@end deffn
775
776@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
af1323c5 777Evaluate each @var{expr} in parallel, each in its own thread, then bind
07d83abe
MV
778the results to the corresponding @var{var} variables and evaluate
779@var{body}.
780
781@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
782expressions for the bindings are evaluated in parallel.
783@end deffn
784
785@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
786@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
787Call @var{proc} on the elements of the given lists. @code{par-map}
788returns a list comprising the return values from @var{proc}.
789@code{par-for-each} returns an unspecified value, but waits for all
790calls to complete.
791
792The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
793@var{elemN})}, where each @var{elem} is from the corresponding
794@var{lst}. Each @var{lst} must be the same length. The calls are
af1323c5 795made in parallel, each in its own thread.
07d83abe
MV
796
797These functions are like @code{map} and @code{for-each} (@pxref{List
798Mapping}), but make their @var{proc} calls in parallel.
799@end deffn
800
801@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
802@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
803Call @var{proc} on the elements of the given lists, in the same way as
804@code{par-map} and @code{par-for-each} above, but use no more than
af1323c5 805@var{n} threads at any one time. The order in which calls are
07d83abe
MV
806initiated within that threads limit is unspecified.
807
808These functions are good for controlling resource consumption if
809@var{proc} calls might be costly, or if there are many to be made. On
810a dual-CPU system for instance @math{@var{n}=4} might be enough to
811keep the CPUs utilized, and not consume too much memory.
812@end deffn
813
814@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
815Apply @var{pproc} to the elements of the given lists, and apply
816@var{sproc} to each result returned by @var{pproc}. The final return
817value is unspecified, but all calls will have been completed before
818returning.
819
820The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
821@var{elemN}))}, where each @var{elem} is from the corresponding
822@var{lst}. Each @var{lst} must have the same number of elements.
823
af1323c5
KR
824The @var{pproc} calls are made in parallel, in separate threads. No more
825than @var{n} threads are used at any one time. The order in which
07d83abe
MV
826@var{pproc} calls are initiated within that limit is unspecified.
827
828The @var{sproc} calls are made serially, in list element order, one at
829a time. @var{pproc} calls on later elements may execute in parallel
830with the @var{sproc} calls. Exactly which thread makes each
831@var{sproc} call is unspecified.
832
833This function is designed for individual calculations that can be done
834in parallel, but with results needing to be handled serially, for
835instance to write them to a file. The @var{n} limit on threads
836controls system resource usage when there are many calculations or
837when they might be costly.
838
839It will be seen that @code{n-for-each-par-map} is like a combination
840of @code{n-par-map} and @code{for-each},
841
842@example
af1323c5 843(for-each sproc (n-par-map n pproc lst1 ... lstN))
07d83abe
MV
844@end example
845
846@noindent
847But the actual implementation is more efficient since each @var{sproc}
848call, in turn, can be initiated once the relevant @var{pproc} call has
849completed, it doesn't need to wait for all to finish.
850@end deffn
851
852
3cf066df 853
07d83abe
MV
854@c Local Variables:
855@c TeX-master: "guile.texi"
856@c End: