Avoid uses of "resp. signed"
[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.
0d4e6ca3 3@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009, 2010
07d83abe
MV
4@c Free Software Foundation, Inc.
5@c See the file guile.texi for copying conditions.
6
07d83abe
MV
7@node Scheduling
8@section Threads, Mutexes, Asyncs and Dynamic Roots
9
07d83abe
MV
10@menu
11* Arbiters:: Synchronization primitives.
12* Asyncs:: Asynchronous procedure invocation.
07d83abe 13* Threads:: Multiple threads of execution.
2567692a 14* Mutexes and Condition Variables:: Synchronization primitives.
b4fddbbe 15* Blocking:: How to block properly in guile mode.
2567692a 16* Critical Sections:: Avoiding concurrency and reentries.
b4fddbbe 17* Fluids and Dynamic States:: Thread-local variables, etc.
0d4e6ca3 18* Futures:: Fine-grain parallelism.
07d83abe
MV
19* Parallel Forms:: Parallel execution of forms.
20@end menu
21
22
23@node Arbiters
24@subsection Arbiters
07d83abe
MV
25@cindex arbiters
26
e136aab0
KR
27Arbiters are synchronization objects, they can be used by threads to
28control access to a shared resource. An arbiter can be locked to
29indicate a resource is in use, and unlocked when done.
07d83abe 30
b4fddbbe
MV
31An arbiter is like a light-weight mutex (@pxref{Mutexes and Condition
32Variables}). It uses less memory and may be faster, but there's no
33way for a thread to block waiting on an arbiter, it can only test and
34get the status returned.
07d83abe
MV
35
36@deffn {Scheme Procedure} make-arbiter name
37@deffnx {C Function} scm_make_arbiter (name)
cdf1ad3b
MV
38Return an object of type arbiter and name @var{name}. Its
39state is initially unlocked. Arbiters are a way to achieve
40process synchronization.
07d83abe
MV
41@end deffn
42
43@deffn {Scheme Procedure} try-arbiter arb
44@deffnx {C Function} scm_try_arbiter (arb)
cdf1ad3b
MV
45If @var{arb} is unlocked, then lock it and return @code{#t}.
46If @var{arb} is already locked, then do nothing and return
47@code{#f}.
07d83abe
MV
48@end deffn
49
50@deffn {Scheme Procedure} release-arbiter arb
51@deffnx {C Function} scm_release_arbiter (arb)
e136aab0
KR
52If @var{arb} is locked, then unlock it and return @code{#t}. If
53@var{arb} is already unlocked, then do nothing and return @code{#f}.
54
55Typical usage is for the thread which locked an arbiter to later
56release it, but that's not required, any thread can release it.
07d83abe
MV
57@end deffn
58
59
60@node Asyncs
61@subsection Asyncs
62
63@cindex asyncs
64@cindex user asyncs
65@cindex system asyncs
66
1021bb7a 67Asyncs are a means of deferring the execution of Scheme code until it is
07d83abe
MV
68safe to do so.
69
70Guile provides two kinds of asyncs that share the basic concept but are
71otherwise quite different: system asyncs and user asyncs. System asyncs
72are integrated into the core of Guile and are executed automatically
73when the system is in a state to allow the execution of Scheme code.
74For example, it is not possible to execute Scheme code in a POSIX signal
75handler, but such a signal handler can queue a system async to be
76executed in the near future, when it is safe to do so.
77
78System asyncs can also be queued for threads other than the current one.
79This way, you can cause threads to asynchronously execute arbitrary
80code.
81
82User asyncs offer a convenient means of queueing procedures for future
83execution and triggering this execution. They will not be executed
84automatically.
85
86@menu
74926120
NJ
87* System asyncs::
88* User asyncs::
07d83abe
MV
89@end menu
90
91@node System asyncs
92@subsubsection System asyncs
93
94To cause the future asynchronous execution of a procedure in a given
95thread, use @code{system-async-mark}.
96
97Automatic invocation of system asyncs can be temporarily disabled by
98calling @code{call-with-blocked-asyncs}. This function works by
99temporarily increasing the @emph{async blocking level} of the current
100thread while a given procedure is running. The blocking level starts
101out at zero, and whenever a safe point is reached, a blocking level
102greater than zero will prevent the execution of queued asyncs.
103
104Analogously, the procedure @code{call-with-unblocked-asyncs} will
105temporarily decrease the blocking level of the current thread. You
106can use it when you want to disable asyncs by default and only allow
107them temporarily.
108
109In addition to the C versions of @code{call-with-blocked-asyncs} and
110@code{call-with-unblocked-asyncs}, C code can use
661ae7ab
MV
111@code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
112inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
113unblock system asyncs temporarily.
07d83abe
MV
114
115@deffn {Scheme Procedure} system-async-mark proc [thread]
116@deffnx {C Function} scm_system_async_mark (proc)
117@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
118Mark @var{proc} (a procedure with zero arguments) for future execution
119in @var{thread}. When @var{proc} has already been marked for
120@var{thread} but has not been executed yet, this call has no effect.
121When @var{thread} is omitted, the thread that called
122@code{system-async-mark} is used.
123
124This procedure is not safe to be called from signal handlers. Use
125@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
126signal handlers.
127@end deffn
128
07d83abe
MV
129@deffn {Scheme Procedure} call-with-blocked-asyncs proc
130@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
07d83abe
MV
131Call @var{proc} and block the execution of system asyncs by one level
132for the current thread while it is running. Return the value returned
133by @var{proc}. For the first two variants, call @var{proc} with no
134arguments; for the third, call it with @var{data}.
135@end deffn
136
1021bb7a
NJ
137@deftypefn {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
138The same but with a C function @var{proc} instead of a Scheme thunk.
139@end deftypefn
140
07d83abe
MV
141@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
142@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
07d83abe
MV
143Call @var{proc} and unblock the execution of system asyncs by one
144level for the current thread while it is running. Return the value
145returned by @var{proc}. For the first two variants, call @var{proc}
146with no arguments; for the third, call it with @var{data}.
147@end deffn
148
1021bb7a
NJ
149@deftypefn {C Function} {void *} scm_c_call_with_unblocked_asyncs (void *(*proc) (void *data), void *data)
150The same but with a C function @var{proc} instead of a Scheme thunk.
151@end deftypefn
152
661ae7ab 153@deftypefn {C Function} void scm_dynwind_block_asyncs ()
1021bb7a
NJ
154During the current dynwind context, increase the blocking of asyncs by
155one level. This function must be used inside a pair of calls to
661ae7ab 156@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
1021bb7a 157Wind}).
07d83abe
MV
158@end deftypefn
159
661ae7ab 160@deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
1021bb7a
NJ
161During the current dynwind context, decrease the blocking of asyncs by
162one level. This function must be used inside a pair of calls to
661ae7ab 163@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
1021bb7a 164Wind}).
07d83abe
MV
165@end deftypefn
166
167@node User asyncs
168@subsubsection User asyncs
169
170A user async is a pair of a thunk (a parameterless procedure) and a
171mark. Setting the mark on a user async will cause the thunk to be
172executed when the user async is passed to @code{run-asyncs}. Setting
173the mark more than once is satisfied by one execution of the thunk.
174
175User asyncs are created with @code{async}. They are marked with
176@code{async-mark}.
177
178@deffn {Scheme Procedure} async thunk
179@deffnx {C Function} scm_async (thunk)
180Create a new user async for the procedure @var{thunk}.
181@end deffn
182
183@deffn {Scheme Procedure} async-mark a
184@deffnx {C Function} scm_async_mark (a)
185Mark the user async @var{a} for future execution.
186@end deffn
187
188@deffn {Scheme Procedure} run-asyncs list_of_a
189@deffnx {C Function} scm_run_asyncs (list_of_a)
190Execute all thunks from the marked asyncs of the list @var{list_of_a}.
191@end deffn
192
07d83abe
MV
193@node Threads
194@subsection Threads
195@cindex threads
196@cindex Guile threads
197@cindex POSIX threads
198
0d4e6ca3
LC
199Guile supports POSIX threads, unless it was configured with
200@code{--without-threads} or the host lacks POSIX thread support. When
201thread support is available, the @code{threads} feature is provided
202(@pxref{Feature Manipulation, @code{provided?}}).
203
204The procedures below manipulate Guile threads, which are wrappers around
205the system's POSIX threads. For application-level parallelism, using
206higher-level constructs, such as futures, is recommended
207(@pxref{Futures}).
208
cdf1ad3b
MV
209@deffn {Scheme Procedure} all-threads
210@deffnx {C Function} scm_all_threads ()
211Return a list of all threads.
212@end deffn
213
214@deffn {Scheme Procedure} current-thread
215@deffnx {C Function} scm_current_thread ()
216Return the thread that called this function.
217@end deffn
07d83abe
MV
218
219@c begin (texi-doc-string "guile" "call-with-new-thread")
23f2b9a3 220@deffn {Scheme Procedure} call-with-new-thread thunk [handler]
b4fddbbe
MV
221Call @code{thunk} in a new thread and with a new dynamic state,
222returning the new thread. The procedure @var{thunk} is called via
223@code{with-continuation-barrier}.
07d83abe 224
b4fddbbe
MV
225When @var{handler} is specified, then @var{thunk} is called from
226within a @code{catch} with tag @code{#t} that has @var{handler} as its
227handler. This catch is established inside the continuation barrier.
07d83abe 228
b4fddbbe
MV
229Once @var{thunk} or @var{handler} returns, the return value is made
230the @emph{exit value} of the thread and the thread is terminated.
07d83abe
MV
231@end deffn
232
b4fddbbe
MV
233@deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
234Call @var{body} in a new thread, passing it @var{body_data}, returning
235the new thread. The function @var{body} is called via
236@code{scm_c_with_continuation_barrier}.
237
238When @var{handler} is non-@code{NULL}, @var{body} is called via
239@code{scm_internal_catch} with tag @code{SCM_BOOL_T} that has
240@var{handler} and @var{handler_data} as the handler and its data. This
241catch is established inside the continuation barrier.
242
243Once @var{body} or @var{handler} returns, the return value is made the
244@emph{exit value} of the thread and the thread is terminated.
245@end deftypefn
246
6180e336
NJ
247@deffn {Scheme Procedure} thread? obj
248@deffnx {C Function} scm_thread_p (obj)
249Return @code{#t} iff @var{obj} is a thread; otherwise, return
250@code{#f}.
251@end deffn
252
07d83abe 253@c begin (texi-doc-string "guile" "join-thread")
6180e336 254@deffn {Scheme Procedure} join-thread thread [timeout [timeoutval]]
300b1ae5 255@deffnx {C Function} scm_join_thread (thread)
6180e336 256@deffnx {C Function} scm_join_thread_timed (thread, timeout, timeoutval)
b4fddbbe
MV
257Wait for @var{thread} to terminate and return its exit value. Threads
258that have not been created with @code{call-with-new-thread} or
74926120 259@code{scm_spawn_thread} have an exit value of @code{#f}. When
6180e336 260@var{timeout} is given, it specifies a point in time where the waiting
74926120
NJ
261should be aborted. It can be either an integer as returned by
262@code{current-time} or a pair as returned by @code{gettimeofday}.
263When the waiting is aborted, @var{timeoutval} is returned (if it is
6180e336 264specified; @code{#f} is returned otherwise).
07d83abe
MV
265@end deffn
266
cdf1ad3b
MV
267@deffn {Scheme Procedure} thread-exited? thread
268@deffnx {C Function} scm_thread_exited_p (thread)
269Return @code{#t} iff @var{thread} has exited.
270@end deffn
271
07d83abe
MV
272@c begin (texi-doc-string "guile" "yield")
273@deffn {Scheme Procedure} yield
274If one or more threads are waiting to execute, calling yield forces an
275immediate context switch to one of them. Otherwise, yield has no effect.
276@end deffn
277
07e02175
LC
278@deffn {Scheme Procedure} cancel-thread thread
279@deffnx {C Function} scm_cancel_thread (thread)
280Asynchronously notify @var{thread} to exit. Immediately after
281receiving this notification, @var{thread} will call its cleanup handler
282(if one has been set) and then terminate, aborting any evaluation that
283is in progress.
284
285Because Guile threads are isomorphic with POSIX threads, @var{thread}
286will not receive its cancellation signal until it reaches a cancellation
287point. See your operating system's POSIX threading documentation for
288more information on cancellation points; note that in Guile, unlike
289native POSIX threads, a thread can receive a cancellation notification
290while attempting to lock a mutex.
291@end deffn
292
293@deffn {Scheme Procedure} set-thread-cleanup! thread proc
294@deffnx {C Function} scm_set_thread_cleanup_x (thread, proc)
295Set @var{proc} as the cleanup handler for the thread @var{thread}.
296@var{proc}, which must be a thunk, will be called when @var{thread}
297exits, either normally or by being canceled. Thread cleanup handlers
298can be used to perform useful tasks like releasing resources, such as
299locked mutexes, when thread exit cannot be predicted.
300
301The return value of @var{proc} will be set as the @emph{exit value} of
302@var{thread}.
303
304To remove a cleanup handler, pass @code{#f} for @var{proc}.
305@end deffn
306
307@deffn {Scheme Procedure} thread-cleanup thread
308@deffnx {C Function} scm_thread_cleanup (thread)
309Return the cleanup handler currently installed for the thread
310@var{thread}. If no cleanup handler is currently installed,
311thread-cleanup returns @code{#f}.
312@end deffn
313
07d83abe
MV
314Higher level thread procedures are available by loading the
315@code{(ice-9 threads)} module. These provide standardized
3cf066df 316thread creation.
07d83abe
MV
317
318@deffn macro make-thread proc [args@dots{}]
319Apply @var{proc} to @var{args} in a new thread formed by
320@code{call-with-new-thread} using a default error handler that display
b4fddbbe
MV
321the error to the current error port. The @var{args@dots{}}
322expressions are evaluated in the new thread.
07d83abe
MV
323@end deffn
324
325@deffn macro begin-thread first [rest@dots{}]
326Evaluate forms @var{first} and @var{rest} in a new thread formed by
327@code{call-with-new-thread} using a default error handler that display
328the error to the current error port.
329@end deffn
330
2567692a
MV
331@node Mutexes and Condition Variables
332@subsection Mutexes and Condition Variables
333@cindex mutex
334@cindex condition variable
335
336A mutex is a thread synchronization object, it can be used by threads
337to control access to a shared resource. A mutex can be locked to
338indicate a resource is in use, and other threads can then block on the
339mutex to wait for the resource (or can just test and do something else
340if not available). ``Mutex'' is short for ``mutual exclusion''.
341
342There are two types of mutexes in Guile, ``standard'' and
343``recursive''. They're created by @code{make-mutex} and
344@code{make-recursive-mutex} respectively, the operation functions are
345then common to both.
346
347Note that for both types of mutex there's no protection against a
348``deadly embrace''. For instance if one thread has locked mutex A and
349is waiting on mutex B, but another thread owns B and is waiting on A,
350then an endless wait will occur (in the current implementation).
351Acquiring requisite mutexes in a fixed order (like always A before B)
352in all threads is one way to avoid such problems.
353
354@sp 1
6180e336 355@deffn {Scheme Procedure} make-mutex . flags
2567692a 356@deffnx {C Function} scm_make_mutex ()
9c9b203b 357@deffnx {C Function} scm_make_mutex_with_flags (SCM flags)
74926120 358Return a new mutex. It is initially unlocked. If @var{flags} is
6180e336 359specified, it must be a list of symbols specifying configuration flags
74926120 360for the newly-created mutex. The supported flags are:
6180e336
NJ
361@table @code
362@item unchecked-unlock
363Unless this flag is present, a call to `unlock-mutex' on the returned
364mutex when it is already unlocked will cause an error to be signalled.
365
366@item allow-external-unlock
367Allow the returned mutex to be unlocked by the calling thread even if
368it was originally locked by a different thread.
369
370@item recursive
371The returned mutex will be recursive.
372
373@end table
374@end deffn
375
376@deffn {Scheme Procedure} mutex? obj
377@deffnx {C Function} scm_mutex_p (obj)
74926120 378Return @code{#t} iff @var{obj} is a mutex; otherwise, return
6180e336 379@code{#f}.
2567692a
MV
380@end deffn
381
382@deffn {Scheme Procedure} make-recursive-mutex
383@deffnx {C Function} scm_make_recursive_mutex ()
6180e336
NJ
384Create a new recursive mutex. It is initially unlocked. Calling this
385function is equivalent to calling `make-mutex' and specifying the
386@code{recursive} flag.
2567692a
MV
387@end deffn
388
adc085f1 389@deffn {Scheme Procedure} lock-mutex mutex [timeout [owner]]
2567692a 390@deffnx {C Function} scm_lock_mutex (mutex)
adc085f1 391@deffnx {C Function} scm_lock_mutex_timed (mutex, timeout, owner)
74926120 392Lock @var{mutex}. If the mutex is already locked, then block and
adc085f1 393return only when @var{mutex} has been acquired.
2567692a 394
74926120
NJ
395When @var{timeout} is given, it specifies a point in time where the
396waiting should be aborted. It can be either an integer as returned
397by @code{current-time} or a pair as returned by @code{gettimeofday}.
398When the waiting is aborted, @code{#f} is returned.
6180e336 399
adc085f1 400When @var{owner} is given, it specifies an owner for @var{mutex} other
74926120 401than the calling thread. @var{owner} may also be @code{#f},
adc085f1
JG
402indicating that the mutex should be locked but left unowned.
403
2567692a
MV
404For standard mutexes (@code{make-mutex}), and error is signalled if
405the thread has itself already locked @var{mutex}.
406
407For a recursive mutex (@code{make-recursive-mutex}), if the thread has
408itself already locked @var{mutex}, then a further @code{lock-mutex}
409call increments the lock count. An additional @code{unlock-mutex}
410will be required to finally release.
411
6180e336 412If @var{mutex} was locked by a thread that exited before unlocking it,
74926120 413the next attempt to lock @var{mutex} will succeed, but
6180e336
NJ
414@code{abandoned-mutex-error} will be signalled.
415
2567692a
MV
416When a system async (@pxref{System asyncs}) is activated for a thread
417blocked in @code{lock-mutex}, the wait is interrupted and the async is
418executed. When the async returns, the wait resumes.
419@end deffn
420
661ae7ab
MV
421@deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
422Arrange for @var{mutex} to be locked whenever the current dynwind
423context is entered and to be unlocked when it is exited.
2567692a 424@end deftypefn
74926120 425
2567692a
MV
426@deffn {Scheme Procedure} try-mutex mx
427@deffnx {C Function} scm_try_mutex (mx)
428Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
429be acquired immediately then this is done and the return is @code{#t}.
430If @var{mutex} is locked by some other thread then nothing is done and
431the return is @code{#f}.
432@end deffn
433
6180e336 434@deffn {Scheme Procedure} unlock-mutex mutex [condvar [timeout]]
2567692a 435@deffnx {C Function} scm_unlock_mutex (mutex)
6180e336
NJ
436@deffnx {C Function} scm_unlock_mutex_timed (mutex, condvar, timeout)
437Unlock @var{mutex}. An error is signalled if @var{mutex} is not locked
74926120 438and was not created with the @code{unchecked-unlock} flag set, or if
6180e336
NJ
439@var{mutex} is locked by a thread other than the calling thread and was
440not created with the @code{allow-external-unlock} flag set.
441
442If @var{condvar} is given, it specifies a condition variable upon
443which the calling thread will wait to be signalled before returning.
74926120 444(This behavior is very similar to that of
6180e336
NJ
445@code{wait-condition-variable}, except that the mutex is left in an
446unlocked state when the function returns.)
447
74926120
NJ
448When @var{timeout} is also given, it specifies a point in time where
449the waiting should be aborted. It can be either an integer as
450returned by @code{current-time} or a pair as returned by
451@code{gettimeofday}. When the waiting is aborted, @code{#f} is
6180e336 452returned. Otherwise the function returns @code{#t}.
2567692a
MV
453@end deffn
454
adc085f1
JG
455@deffn {Scheme Procedure} mutex-owner mutex
456@deffnx {C Function} scm_mutex_owner (mutex)
74926120 457Return the current owner of @var{mutex}, in the form of a thread or
adc085f1
JG
458@code{#f} (indicating no owner). Note that a mutex may be unowned but
459still locked.
460@end deffn
461
462@deffn {Scheme Procedure} mutex-level mutex
463@deffnx {C Function} scm_mutex_level (mutex)
464Return the current lock level of @var{mutex}. If @var{mutex} is
465currently unlocked, this value will be 0; otherwise, it will be the
466number of times @var{mutex} has been recursively locked by its current
467owner.
468@end deffn
469
470@deffn {Scheme Procedure} mutex-locked? mutex
471@deffnx {C Function} scm_mutex_locked_p (mutex)
472Return @code{#t} if @var{mutex} is locked, regardless of ownership;
473otherwise, return @code{#f}.
474@end deffn
475
2567692a
MV
476@deffn {Scheme Procedure} make-condition-variable
477@deffnx {C Function} scm_make_condition_variable ()
478Return a new condition variable.
479@end deffn
480
6180e336
NJ
481@deffn {Scheme Procedure} condition-variable? obj
482@deffnx {C Function} scm_condition_variable_p (obj)
74926120 483Return @code{#t} iff @var{obj} is a condition variable; otherwise,
6180e336
NJ
484return @code{#f}.
485@end deffn
486
2567692a
MV
487@deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
488@deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
489Wait until @var{condvar} has been signalled. While waiting,
490@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
491is locked again when this function returns. When @var{time} is given,
492it specifies a point in time where the waiting should be aborted. It
493can be either a integer as returned by @code{current-time} or a pair
494as returned by @code{gettimeofday}. When the waiting is aborted,
495@code{#f} is returned. When the condition variable has in fact been
496signalled, @code{#t} is returned. The mutex is re-locked in any case
497before @code{wait-condition-variable} returns.
498
499When a system async is activated for a thread that is blocked in a
500call to @code{wait-condition-variable}, the waiting is interrupted,
501the mutex is locked, and the async is executed. When the async
502returns, the mutex is unlocked again and the waiting is resumed. When
503the thread block while re-acquiring the mutex, execution of asyncs is
504blocked.
505@end deffn
506
507@deffn {Scheme Procedure} signal-condition-variable condvar
508@deffnx {C Function} scm_signal_condition_variable (condvar)
509Wake up one thread that is waiting for @var{condvar}.
510@end deffn
511
512@deffn {Scheme Procedure} broadcast-condition-variable condvar
513@deffnx {C Function} scm_broadcast_condition_variable (condvar)
514Wake up all threads that are waiting for @var{condvar}.
515@end deffn
516
517@sp 1
518The following are higher level operations on mutexes. These are
519available from
520
521@example
522(use-modules (ice-9 threads))
523@end example
524
525@deffn macro with-mutex mutex [body@dots{}]
526Lock @var{mutex}, evaluate the @var{body} forms, then unlock
527@var{mutex}. The return value is the return from the last @var{body}
528form.
529
530The lock, body and unlock form the branches of a @code{dynamic-wind}
531(@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
532error or new continuation exits @var{body}, and is re-locked if
533@var{body} is re-entered by a captured continuation.
534@end deffn
535
536@deffn macro monitor body@dots{}
537Evaluate the @var{body} forms, with a mutex locked so only one thread
538can execute that code at any one time. The return value is the return
539from the last @var{body} form.
540
541Each @code{monitor} form has its own private mutex and the locking and
542evaluation is as per @code{with-mutex} above. A standard mutex
543(@code{make-mutex}) is used, which means @var{body} must not
544recursively re-enter the @code{monitor} form.
545
546The term ``monitor'' comes from operating system theory, where it
547means a particular bit of code managing access to some resource and
548which only ever executes on behalf of one process at any one time.
549@end deffn
550
551
b4fddbbe
MV
552@node Blocking
553@subsection Blocking in Guile Mode
07d83abe 554
d3d66147
LC
555Up to Guile version 1.8, a thread blocked in guile mode would prevent
556the garbage collector from running. Thus threads had to explicitly
557leave guile mode with @code{scm_without_guile ()} before making a
558potentially blocking call such as a mutex lock, a @code{select ()}
559system call, etc. The following functions could be used to temporarily
560leave guile mode or to perform some common blocking operations in a
561supported way.
562
563Starting from Guile 2.0, blocked threads no longer hinder garbage
564collection. Thus, the functions below are not needed anymore. They can
565still be used to inform the GC that a thread is about to block, giving
566it a (small) optimization opportunity for ``stop the world'' garbage
567collections, should they occur while the thread is blocked.
07d83abe 568
54428bb8
MV
569@deftypefn {C Function} {void *} scm_without_guile (void *(*func) (void *), void *data)
570Leave guile mode, call @var{func} on @var{data}, enter guile mode and
571return the result of calling @var{func}.
07d83abe 572
b4fddbbe 573While a thread has left guile mode, it must not call any libguile
54428bb8
MV
574functions except @code{scm_with_guile} or @code{scm_without_guile} and
575must not use any libguile macros. Also, local variables of type
576@code{SCM} that are allocated while not in guile mode are not
577protected from the garbage collector.
578
579When used from non-guile mode, calling @code{scm_without_guile} is
580still allowed: it simply calls @var{func}. In that way, you can leave
581guile mode without having to know whether the current thread is in
582guile mode or not.
07d83abe
MV
583@end deftypefn
584
b4fddbbe
MV
585@deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
586Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
587the mutex.
07d83abe
MV
588@end deftypefn
589
b4fddbbe
MV
590@deftypefn {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
591@deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
592Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
593leaves guile mode while waiting for the condition variable.
07d83abe
MV
594@end deftypefn
595
b4fddbbe
MV
596@deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
597Like @code{select} but leaves guile mode while waiting. Also, the
598delivery of a system async causes this function to be interrupted with
599error code @code{EINTR}.
07d83abe
MV
600@end deftypefn
601
b4fddbbe
MV
602@deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
603Like @code{sleep}, but leaves guile mode while sleeping. Also, the
604delivery of a system async causes this function to be interrupted.
07d83abe
MV
605@end deftypefn
606
b4fddbbe
MV
607@deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
608Like @code{usleep}, but leaves guile mode while sleeping. Also, the
609delivery of a system async causes this function to be interrupted.
07d83abe
MV
610@end deftypefn
611
07d83abe 612
2567692a
MV
613@node Critical Sections
614@subsection Critical Sections
615
616@deffn {C Macro} SCM_CRITICAL_SECTION_START
617@deffnx {C Macro} SCM_CRITICAL_SECTION_END
618These two macros can be used to delimit a critical section.
619Syntactically, they are both statements and need to be followed
620immediately by a semicolon.
621
622Executing @code{SCM_CRITICAL_SECTION_START} will lock a recursive
623mutex and block the executing of system asyncs. Executing
624@code{SCM_CRITICAL_SECTION_END} will unblock the execution of system
625asyncs and unlock the mutex. Thus, the code that executes between
626these two macros can only be executed in one thread at any one time
627and no system asyncs will run. However, because the mutex is a
628recursive one, the code might still be reentered by the same thread.
629You must either allow for this or avoid it, both by careful coding.
630
631On the other hand, critical sections delimited with these macros can
632be nested since the mutex is recursive.
633
634You must make sure that for each @code{SCM_CRITICAL_SECTION_START},
635the corresponding @code{SCM_CRITICAL_SECTION_END} is always executed.
636This means that no non-local exit (such as a signalled error) might
637happen, for example.
638@end deffn
639
661ae7ab
MV
640@deftypefn {C Function} void scm_dynwind_critical_section (SCM mutex)
641Call @code{scm_dynwind_lock_mutex} on @var{mutex} and call
642@code{scm_dynwind_block_asyncs}. When @var{mutex} is false, a recursive
2567692a
MV
643mutex provided by Guile is used instead.
644
661ae7ab
MV
645The effect of a call to @code{scm_dynwind_critical_section} is that
646the current dynwind context (@pxref{Dynamic Wind}) turns into a
647critical section. Because of the locked mutex, no second thread can
648enter it concurrently and because of the blocked asyncs, no system
649async can reenter it from the current thread.
2567692a
MV
650
651When the current thread reenters the critical section anyway, the kind
652of @var{mutex} determines what happens: When @var{mutex} is recursive,
653the reentry is allowed. When it is a normal mutex, an error is
654signalled.
655@end deftypefn
656
657
b4fddbbe
MV
658@node Fluids and Dynamic States
659@subsection Fluids and Dynamic States
07d83abe
MV
660
661@cindex fluids
662
b4fddbbe
MV
663A @emph{fluid} is an object that can store one value per @emph{dynamic
664state}. Each thread has a current dynamic state, and when accessing a
665fluid, this current dynamic state is used to provide the actual value.
666In this way, fluids can be used for thread local storage, but they are
667in fact more flexible: dynamic states are objects of their own and can
668be made current for more than one thread at the same time, or only be
669made current temporarily, for example.
670
671Fluids can also be used to simulate the desirable effects of
672dynamically scoped variables. Dynamically scoped variables are useful
673when you want to set a variable to a value during some dynamic extent
674in the execution of your program and have them revert to their
675original value when the control flow is outside of this dynamic
676extent. See the description of @code{with-fluids} below for details.
07d83abe
MV
677
678New fluids are created with @code{make-fluid} and @code{fluid?} is
679used for testing whether an object is actually a fluid. The values
680stored in a fluid can be accessed with @code{fluid-ref} and
681@code{fluid-set!}.
682
683@deffn {Scheme Procedure} make-fluid
684@deffnx {C Function} scm_make_fluid ()
685Return a newly created fluid.
b4fddbbe
MV
686Fluids are objects that can hold one
687value per dynamic state. That is, modifications to this value are
688only visible to code that executes with the same dynamic state as
689the modifying code. When a new dynamic state is constructed, it
690inherits the values from its parent. Because each thread normally executes
691with its own dynamic state, you can use fluids for thread local storage.
07d83abe
MV
692@end deffn
693
d09c07fb
AW
694@deffn {Scheme Procedure} make-unbound-fluid
695@deffnx {C Function} scm_make_unbound_fluid ()
696Return a new fluid that is initially unbound (instead of being
697implicitly bound to @code{#f}.
698@end deffn
699
07d83abe
MV
700@deffn {Scheme Procedure} fluid? obj
701@deffnx {C Function} scm_fluid_p (obj)
702Return @code{#t} iff @var{obj} is a fluid; otherwise, return
703@code{#f}.
704@end deffn
705
706@deffn {Scheme Procedure} fluid-ref fluid
707@deffnx {C Function} scm_fluid_ref (fluid)
708Return the value associated with @var{fluid} in the current
709dynamic root. If @var{fluid} has not been set, then return
d09c07fb
AW
710@code{#f}. Calling @code{fluid-ref} on an unbound fluid produces a
711runtime error.
07d83abe
MV
712@end deffn
713
714@deffn {Scheme Procedure} fluid-set! fluid value
715@deffnx {C Function} scm_fluid_set_x (fluid, value)
716Set the value associated with @var{fluid} in the current dynamic root.
717@end deffn
718
d09c07fb
AW
719@deffn {Scheme Procedure} fluid-unset! fluid
720@deffnx {C Function} scm_fluid_unset_x (fluid)
721Disassociate the given fluid from any value, making it unbound.
722@end deffn
723
724@deffn {Scheme Procedure} fluid-bound? fluid
725@deffnx {C Function} scm_fluid_bound_p (fluid)
726Returns @code{#t} iff the given fluid is bound to a value, otherwise
727@code{#f}.
728@end deffn
729
07d83abe
MV
730@code{with-fluids*} temporarily changes the values of one or more fluids,
731so that the given procedure and each procedure called by it access the
732given values. After the procedure returns, the old values are restored.
733
cdf1ad3b
MV
734@deffn {Scheme Procedure} with-fluid* fluid value thunk
735@deffnx {C Function} scm_with_fluid (fluid, value, thunk)
736Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
737@var{thunk} must be a procedure with no argument.
738@end deffn
739
07d83abe
MV
740@deffn {Scheme Procedure} with-fluids* fluids values thunk
741@deffnx {C Function} scm_with_fluids (fluids, values, thunk)
742Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
743@var{fluids} must be a list of fluids and @var{values} must be the
744same number of their values to be applied. Each substitution is done
745in the order given. @var{thunk} must be a procedure with no argument.
ecb87335 746It is called inside a @code{dynamic-wind} and the fluids are
07d83abe
MV
747set/restored when control enter or leaves the established dynamic
748extent.
749@end deffn
750
751@deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
752Execute @var{body...} while each @var{fluid} is set to the
753corresponding @var{value}. Both @var{fluid} and @var{value} are
754evaluated and @var{fluid} must yield a fluid. @var{body...} is
755executed inside a @code{dynamic-wind} and the fluids are set/restored
756when control enter or leaves the established dynamic extent.
757@end deffn
758
759@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
760@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
761The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
762except that it takes a C function to call instead of a Scheme thunk.
763
764The function @code{scm_c_with_fluid} is similar but only allows one
765fluid to be set instead of a list.
766@end deftypefn
767
661ae7ab 768@deftypefn {C Function} void scm_dynwind_fluid (SCM fluid, SCM val)
07d83abe 769This function must be used inside a pair of calls to
661ae7ab
MV
770@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
771Wind}). During the dynwind context, the fluid @var{fluid} is set to
772@var{val}.
07d83abe
MV
773
774More precisely, the value of the fluid is swapped with a `backup'
661ae7ab
MV
775value whenever the dynwind context is entered or left. The backup
776value is initialized with the @var{val} argument.
07d83abe
MV
777@end deftypefn
778
b4fddbbe
MV
779@deffn {Scheme Procedure} make-dynamic-state [parent]
780@deffnx {C Function} scm_make_dynamic_state (parent)
781Return a copy of the dynamic state object @var{parent}
782or of the current dynamic state when @var{parent} is omitted.
783@end deffn
784
785@deffn {Scheme Procedure} dynamic-state? obj
786@deffnx {C Function} scm_dynamic_state_p (obj)
787Return @code{#t} if @var{obj} is a dynamic state object;
788return @code{#f} otherwise.
789@end deffn
790
791@deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
792Return non-zero if @var{obj} is a dynamic state object;
793return zero otherwise.
794@end deftypefn
795
796@deffn {Scheme Procedure} current-dynamic-state
797@deffnx {C Function} scm_current_dynamic_state ()
798Return the current dynamic state object.
799@end deffn
800
801@deffn {Scheme Procedure} set-current-dynamic-state state
802@deffnx {C Function} scm_set_current_dynamic_state (state)
803Set the current dynamic state object to @var{state}
804and return the previous current dynamic state object.
805@end deffn
806
807@deffn {Scheme Procedure} with-dynamic-state state proc
808@deffnx {C Function} scm_with_dynamic_state (state, proc)
809Call @var{proc} while @var{state} is the current dynamic
810state object.
811@end deffn
812
661ae7ab
MV
813@deftypefn {C Procedure} void scm_dynwind_current_dynamic_state (SCM state)
814Set the current dynamic state to @var{state} for the current dynwind
815context.
b4fddbbe
MV
816@end deftypefn
817
c2110081 818@deftypefn {C Procedure} {void *} scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
b4fddbbe
MV
819Like @code{scm_with_dynamic_state}, but call @var{func} with
820@var{data}.
821@end deftypefn
822
0d4e6ca3
LC
823@node Futures
824@subsection Futures
825@cindex futures
826@cindex fine-grain parallelism
827@cindex parallelism
828
829The @code{(ice-9 futures)} module provides @dfn{futures}, a construct
830for fine-grain parallelism. A future is a wrapper around an expression
831whose computation may occur in parallel with the code of the calling
832thread, and possibly in parallel with other futures. Like promises,
833futures are essentially proxies that can be queried to obtain the value
834of the enclosed expression:
835
836@lisp
837(touch (future (+ 2 3)))
838@result{} 5
839@end lisp
840
841However, unlike promises, the expression associated with a future may be
842evaluated on another CPU core, should one be available. This supports
843@dfn{fine-grain parallelism}, because even relatively small computations
844can be embedded in futures. Consider this sequential code:
845
846@lisp
847(define (find-prime lst1 lst2)
848 (or (find prime? lst1)
849 (find prime? lst2)))
850@end lisp
851
852The two arms of @code{or} are potentially computation-intensive. They
853are independent of one another, yet, they are evaluated sequentially
854when the first one returns @code{#f}. Using futures, one could rewrite
855it like this:
856
857@lisp
858(define (find-prime lst1 lst2)
859 (let ((f (future (find prime? lst2))))
860 (or (find prime? lst1)
861 (touch f))))
862@end lisp
863
864This preserves the semantics of @code{find-prime}. On a multi-core
865machine, though, the computation of @code{(find prime? lst2)} may be
866done in parallel with that of the other @code{find} call, which can
867reduce the execution time of @code{find-prime}.
868
51fc066a
LC
869Note that futures are intended for the evaluation of purely functional
870expressions. Expressions that have side-effects or rely on I/O may
871require additional care, such as explicit synchronization
872(@pxref{Mutexes and Condition Variables}).
873
0d4e6ca3
LC
874Guile's futures are implemented on top of POSIX threads
875(@pxref{Threads}). Internally, a fixed-size pool of threads is used to
876evaluate futures, such that offloading the evaluation of an expression
877to another thread doesn't incur thread creation costs. By default, the
51fc066a
LC
878pool contains one thread per available CPU core, minus one, to account
879for the main thread. The number of available CPU cores is determined
880using @code{current-processor-count} (@pxref{Processes}).
0d4e6ca3
LC
881
882@deffn {Scheme Syntax} future exp
883Return a future for expression @var{exp}. This is equivalent to:
884
885@lisp
886(make-future (lambda () exp))
887@end lisp
888@end deffn
889
890@deffn {Scheme Procedure} make-future thunk
891Return a future for @var{thunk}, a zero-argument procedure.
892
893This procedure returns immediately. Execution of @var{thunk} may begin
894in parallel with the calling thread's computations, if idle CPU cores
895are available, or it may start when @code{touch} is invoked on the
896returned future.
897
898If the execution of @var{thunk} throws an exception, that exception will
899be re-thrown when @code{touch} is invoked on the returned future.
900@end deffn
901
902@deffn {Scheme Procedure} future? obj
903Return @code{#t} if @var{obj} is a future.
904@end deffn
905
906@deffn {Scheme Procedure} touch f
907Return the result of the expression embedded in future @var{f}.
908
909If the result was already computed in parallel, @code{touch} returns
910instantaneously. Otherwise, it waits for the computation to complete,
911if it already started, or initiates it.
912@end deffn
913
914
07d83abe
MV
915@node Parallel Forms
916@subsection Parallel forms
917@cindex parallel forms
918
919The functions described in this section are available from
920
921@example
922(use-modules (ice-9 threads))
923@end example
924
c21a5ddc
LC
925They provide high-level parallel constructs. The following functions
926are implemented in terms of futures (@pxref{Futures}). Thus they are
927relatively cheap as they re-use existing threads, and portable, since
928they automatically use one thread per available CPU core.
929
07d83abe 930@deffn syntax parallel expr1 @dots{} exprN
af1323c5 931Evaluate each @var{expr} expression in parallel, each in its own thread.
07d83abe
MV
932Return the results as a set of @var{N} multiple values
933(@pxref{Multiple Values}).
934@end deffn
935
936@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
af1323c5 937Evaluate each @var{expr} in parallel, each in its own thread, then bind
07d83abe
MV
938the results to the corresponding @var{var} variables and evaluate
939@var{body}.
940
941@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
942expressions for the bindings are evaluated in parallel.
943@end deffn
944
945@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
946@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
947Call @var{proc} on the elements of the given lists. @code{par-map}
948returns a list comprising the return values from @var{proc}.
949@code{par-for-each} returns an unspecified value, but waits for all
950calls to complete.
951
952The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
953@var{elemN})}, where each @var{elem} is from the corresponding
954@var{lst}. Each @var{lst} must be the same length. The calls are
3e0e4f1d
LC
955potentially made in parallel, depending on the number of CPU cores
956available.
07d83abe
MV
957
958These functions are like @code{map} and @code{for-each} (@pxref{List
959Mapping}), but make their @var{proc} calls in parallel.
960@end deffn
961
c21a5ddc
LC
962Unlike those above, the functions described below take a number of
963threads as an argument. This makes them inherently non-portable since
964the specified number of threads may differ from the number of available
965CPU cores as returned by @code{current-processor-count}
966(@pxref{Processes}). In addition, these functions create the specified
967number of threads when they are called and terminate them upon
968completion, which makes them quite expensive.
969
970Therefore, they should be avoided.
971
07d83abe
MV
972@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
973@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
974Call @var{proc} on the elements of the given lists, in the same way as
975@code{par-map} and @code{par-for-each} above, but use no more than
af1323c5 976@var{n} threads at any one time. The order in which calls are
07d83abe
MV
977initiated within that threads limit is unspecified.
978
979These functions are good for controlling resource consumption if
980@var{proc} calls might be costly, or if there are many to be made. On
981a dual-CPU system for instance @math{@var{n}=4} might be enough to
982keep the CPUs utilized, and not consume too much memory.
983@end deffn
984
985@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
986Apply @var{pproc} to the elements of the given lists, and apply
987@var{sproc} to each result returned by @var{pproc}. The final return
988value is unspecified, but all calls will have been completed before
989returning.
990
991The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
992@var{elemN}))}, where each @var{elem} is from the corresponding
993@var{lst}. Each @var{lst} must have the same number of elements.
994
af1323c5
KR
995The @var{pproc} calls are made in parallel, in separate threads. No more
996than @var{n} threads are used at any one time. The order in which
07d83abe
MV
997@var{pproc} calls are initiated within that limit is unspecified.
998
999The @var{sproc} calls are made serially, in list element order, one at
1000a time. @var{pproc} calls on later elements may execute in parallel
1001with the @var{sproc} calls. Exactly which thread makes each
1002@var{sproc} call is unspecified.
1003
1004This function is designed for individual calculations that can be done
1005in parallel, but with results needing to be handled serially, for
1006instance to write them to a file. The @var{n} limit on threads
1007controls system resource usage when there are many calculations or
1008when they might be costly.
1009
1010It will be seen that @code{n-for-each-par-map} is like a combination
1011of @code{n-par-map} and @code{for-each},
1012
1013@example
af1323c5 1014(for-each sproc (n-par-map n pproc lst1 ... lstN))
07d83abe
MV
1015@end example
1016
1017@noindent
1018But the actual implementation is more efficient since each @var{sproc}
1019call, in turn, can be initiated once the relevant @var{pproc} call has
1020completed, it doesn't need to wait for all to finish.
1021@end deffn
1022
1023
3cf066df 1024
07d83abe
MV
1025@c Local Variables:
1026@c TeX-master: "guile.texi"
1027@c End: