*** empty log message ***
[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.
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.
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.
b4fddbbe
MV
20* Blocking:: How to block properly in guile mode.
21* Fluids and Dynamic States:: Thread-local variables, etc.
07d83abe
MV
22* Futures:: Delayed execution in new threads.
23* Parallel Forms:: Parallel execution of forms.
b4fddbbe 24* Mutexes and Condition Variables:: Synchronization primitives.
07d83abe
MV
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
b4fddbbe 117@code{scm_frame_block_asyncs} and @code{scm_frame_unblock_asyncs}
07d83abe
MV
118inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs
119temporarily.
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)
143@deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
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)
153@deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
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
161@deftypefn {C Function} void scm_frame_block_asyncs ()
162This function must be used inside a pair of calls to
163@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
164During the dynamic extent of the frame, asyncs are blocked by one level.
165@end deftypefn
166
167@deftypefn {C Function} void scm_frame_unblock_asyncs ()
168This function must be used inside a pair of calls to
169@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
170During the dynamic extent of the frame, asyncs are unblocked by one
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
b4fddbbe
MV
207@deffn {Sheme Procedure} with-continuation-barrier proc
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
b4fddbbe
MV
221@deftypefn {C Function} void *scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
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")
b4fddbbe
MV
243@deffn {Scheme Procedure} call-with-new-thread thunk handler
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
b4fddbbe
MV
272Wait for @var{thread} to terminate and return its exit value. Threads
273that have not been created with @code{call-with-new-thread} or
274@code{scm_spawn_thread} have an exit value of @code{#f}.
07d83abe
MV
275@end deffn
276
cdf1ad3b
MV
277@deffn {Scheme Procedure} thread-exited? thread
278@deffnx {C Function} scm_thread_exited_p (thread)
279Return @code{#t} iff @var{thread} has exited.
280@end deffn
281
07d83abe
MV
282@c begin (texi-doc-string "guile" "yield")
283@deffn {Scheme Procedure} yield
284If one or more threads are waiting to execute, calling yield forces an
285immediate context switch to one of them. Otherwise, yield has no effect.
286@end deffn
287
07d83abe
MV
288Higher level thread procedures are available by loading the
289@code{(ice-9 threads)} module. These provide standardized
3cf066df 290thread creation.
07d83abe
MV
291
292@deffn macro make-thread proc [args@dots{}]
293Apply @var{proc} to @var{args} in a new thread formed by
294@code{call-with-new-thread} using a default error handler that display
b4fddbbe
MV
295the error to the current error port. The @var{args@dots{}}
296expressions are evaluated in the new thread.
07d83abe
MV
297@end deffn
298
299@deffn macro begin-thread first [rest@dots{}]
300Evaluate forms @var{first} and @var{rest} in a new thread formed by
301@code{call-with-new-thread} using a default error handler that display
302the error to the current error port.
303@end deffn
304
b4fddbbe
MV
305@node Blocking
306@subsection Blocking in Guile Mode
07d83abe 307
b4fddbbe
MV
308A thread must not block outside of a libguile function while it is in
309guile mode. The following functions can be used to temporily leave
310guile mode or to perform some common blocking operations in a supported
311way.
07d83abe 312
9ba2fab3
MV
313@deftypefn {C Function} scm_t_guile_ticket scm_leave_guile ()
314@deftypefnx {C Function} void scm_enter_guile (scm_t_guile_ticket ticket)
315These two functions must be called as a pair and can be used to leave
316guile mode temporarily. The call to @code{scm_leave_guile} returns a
317ticket that must be used with @code{scm_enter_guile} to match up the two
318calls.
07d83abe 319
b4fddbbe 320While a thread has left guile mode, it must not call any libguile
9ba2fab3
MV
321functions except @code{scm_enter_guile}, @code{scm_with_guile},
322@code{scm_without_guile} or @code{scm_leave_guile} and must not use any
323libguile macros. Also, local variables of type @code{SCM} that are
324allocated while not in guile mode are not protected from the garbage
325collector.
326
327When used from non-guile mode, a pair of calls to @code{scm_leave_guile}
328and @code{scm_enter_guile} do nothing. In that way, you can leave guile
329mode without having to know whether the current thread is in guile mode
330or not.
07d83abe
MV
331@end deftypefn
332
b4fddbbe 333@deftypefn {C Function} void *scm_without_guile (void *(*func) (void *), void *data)
9ba2fab3
MV
334Leave guile mode as with @code{scm_leave_guile}, call @var{func} on
335@var{data}, enter guile mode as with @code{scm_enter_guile} and return
336the result of calling @var{func}.
07d83abe
MV
337@end deftypefn
338
b4fddbbe
MV
339@deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
340Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
341the mutex.
07d83abe
MV
342@end deftypefn
343
b4fddbbe
MV
344@deftypefn {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
345@deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
346Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
347leaves guile mode while waiting for the condition variable.
07d83abe
MV
348@end deftypefn
349
b4fddbbe
MV
350@deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
351Like @code{select} but leaves guile mode while waiting. Also, the
352delivery of a system async causes this function to be interrupted with
353error code @code{EINTR}.
07d83abe
MV
354@end deftypefn
355
b4fddbbe
MV
356@deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
357Like @code{sleep}, but leaves guile mode while sleeping. Also, the
358delivery of a system async causes this function to be interrupted.
07d83abe
MV
359@end deftypefn
360
b4fddbbe
MV
361@deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
362Like @code{usleep}, but leaves guile mode while sleeping. Also, the
363delivery of a system async causes this function to be interrupted.
07d83abe
MV
364@end deftypefn
365
07d83abe 366
b4fddbbe
MV
367@node Fluids and Dynamic States
368@subsection Fluids and Dynamic States
07d83abe
MV
369
370@cindex fluids
371
b4fddbbe
MV
372A @emph{fluid} is an object that can store one value per @emph{dynamic
373state}. Each thread has a current dynamic state, and when accessing a
374fluid, this current dynamic state is used to provide the actual value.
375In this way, fluids can be used for thread local storage, but they are
376in fact more flexible: dynamic states are objects of their own and can
377be made current for more than one thread at the same time, or only be
378made current temporarily, for example.
379
380Fluids can also be used to simulate the desirable effects of
381dynamically scoped variables. Dynamically scoped variables are useful
382when you want to set a variable to a value during some dynamic extent
383in the execution of your program and have them revert to their
384original value when the control flow is outside of this dynamic
385extent. See the description of @code{with-fluids} below for details.
07d83abe
MV
386
387New fluids are created with @code{make-fluid} and @code{fluid?} is
388used for testing whether an object is actually a fluid. The values
389stored in a fluid can be accessed with @code{fluid-ref} and
390@code{fluid-set!}.
391
392@deffn {Scheme Procedure} make-fluid
393@deffnx {C Function} scm_make_fluid ()
394Return a newly created fluid.
b4fddbbe
MV
395Fluids are objects that can hold one
396value per dynamic state. That is, modifications to this value are
397only visible to code that executes with the same dynamic state as
398the modifying code. When a new dynamic state is constructed, it
399inherits the values from its parent. Because each thread normally executes
400with its own dynamic state, you can use fluids for thread local storage.
07d83abe
MV
401@end deffn
402
403@deffn {Scheme Procedure} fluid? obj
404@deffnx {C Function} scm_fluid_p (obj)
405Return @code{#t} iff @var{obj} is a fluid; otherwise, return
406@code{#f}.
407@end deffn
408
409@deffn {Scheme Procedure} fluid-ref fluid
410@deffnx {C Function} scm_fluid_ref (fluid)
411Return the value associated with @var{fluid} in the current
412dynamic root. If @var{fluid} has not been set, then return
413@code{#f}.
414@end deffn
415
416@deffn {Scheme Procedure} fluid-set! fluid value
417@deffnx {C Function} scm_fluid_set_x (fluid, value)
418Set the value associated with @var{fluid} in the current dynamic root.
419@end deffn
420
421@code{with-fluids*} temporarily changes the values of one or more fluids,
422so that the given procedure and each procedure called by it access the
423given values. After the procedure returns, the old values are restored.
424
cdf1ad3b
MV
425@deffn {Scheme Procedure} with-fluid* fluid value thunk
426@deffnx {C Function} scm_with_fluid (fluid, value, thunk)
427Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
428@var{thunk} must be a procedure with no argument.
429@end deffn
430
07d83abe
MV
431@deffn {Scheme Procedure} with-fluids* fluids values thunk
432@deffnx {C Function} scm_with_fluids (fluids, values, thunk)
433Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
434@var{fluids} must be a list of fluids and @var{values} must be the
435same number of their values to be applied. Each substitution is done
436in the order given. @var{thunk} must be a procedure with no argument.
437it is called inside a @code{dynamic-wind} and the fluids are
438set/restored when control enter or leaves the established dynamic
439extent.
440@end deffn
441
442@deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
443Execute @var{body...} while each @var{fluid} is set to the
444corresponding @var{value}. Both @var{fluid} and @var{value} are
445evaluated and @var{fluid} must yield a fluid. @var{body...} is
446executed inside a @code{dynamic-wind} and the fluids are set/restored
447when control enter or leaves the established dynamic extent.
448@end deffn
449
450@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
451@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
452The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
453except that it takes a C function to call instead of a Scheme thunk.
454
455The function @code{scm_c_with_fluid} is similar but only allows one
456fluid to be set instead of a list.
457@end deftypefn
458
459@deftypefn {C Function} void scm_frame_fluid (SCM fluid, SCM val)
460This function must be used inside a pair of calls to
461@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
462During the dynamic extent of the frame, the fluid @var{fluid} is set
463to @var{val}.
464
465More precisely, the value of the fluid is swapped with a `backup'
466value whenever the frame is entered or left. The backup value is
467initialized with the @var{val} argument.
468@end deftypefn
469
b4fddbbe
MV
470@deffn {Scheme Procedure} make-dynamic-state [parent]
471@deffnx {C Function} scm_make_dynamic_state (parent)
472Return a copy of the dynamic state object @var{parent}
473or of the current dynamic state when @var{parent} is omitted.
474@end deffn
475
476@deffn {Scheme Procedure} dynamic-state? obj
477@deffnx {C Function} scm_dynamic_state_p (obj)
478Return @code{#t} if @var{obj} is a dynamic state object;
479return @code{#f} otherwise.
480@end deffn
481
482@deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
483Return non-zero if @var{obj} is a dynamic state object;
484return zero otherwise.
485@end deftypefn
486
487@deffn {Scheme Procedure} current-dynamic-state
488@deffnx {C Function} scm_current_dynamic_state ()
489Return the current dynamic state object.
490@end deffn
491
492@deffn {Scheme Procedure} set-current-dynamic-state state
493@deffnx {C Function} scm_set_current_dynamic_state (state)
494Set the current dynamic state object to @var{state}
495and return the previous current dynamic state object.
496@end deffn
497
498@deffn {Scheme Procedure} with-dynamic-state state proc
499@deffnx {C Function} scm_with_dynamic_state (state, proc)
500Call @var{proc} while @var{state} is the current dynamic
501state object.
502@end deffn
503
504@deftypefn {C Procedure} void scm_frame_current_dynamic_state (SCM state)
505Set the current dynamic state to @var{state} for the dynamic extent of
506the current frame.
507@end deftypefn
508
509@deftypefn {C Procedure} void *scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
510Like @code{scm_with_dynamic_state}, but call @var{func} with
511@var{data}.
512@end deftypefn
513
07d83abe
MV
514@node Futures
515@subsection Futures
516@cindex futures
517
518Futures are a convenient way to run a calculation in a new thread, and
519only wait for the result when it's actually needed.
520
521Futures are similar to promises (@pxref{Delayed Evaluation}), in that
522they allow mainline code to continue immediately. But @code{delay}
523doesn't evaluate at all until forced, whereas @code{future} starts
524immediately in a new thread.
525
526@deffn {syntax} future expr
527Begin evaluating @var{expr} in a new thread, and return a ``future''
528object representing the calculation.
529@end deffn
530
531@deffn {Scheme Procedure} make-future thunk
532@deffnx {C Function} scm_make_future (thunk)
533Begin evaluating the call @code{(@var{thunk})} in a new thread, and
534return a ``future'' object representing the calculation.
535@end deffn
536
537@deffn {Scheme Procedure} future-ref f
538@deffnx {C Function} scm_future_ref (f)
539Return the value computed by the future @var{f}. If @var{f} has not
540yet finished executing then wait for it to do so.
541@end deffn
542
543
544@node Parallel Forms
545@subsection Parallel forms
546@cindex parallel forms
547
548The functions described in this section are available from
549
550@example
551(use-modules (ice-9 threads))
552@end example
553
554@deffn syntax parallel expr1 @dots{} exprN
af1323c5 555Evaluate each @var{expr} expression in parallel, each in its own thread.
07d83abe
MV
556Return the results as a set of @var{N} multiple values
557(@pxref{Multiple Values}).
558@end deffn
559
560@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
af1323c5 561Evaluate each @var{expr} in parallel, each in its own thread, then bind
07d83abe
MV
562the results to the corresponding @var{var} variables and evaluate
563@var{body}.
564
565@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
566expressions for the bindings are evaluated in parallel.
567@end deffn
568
569@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
570@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
571Call @var{proc} on the elements of the given lists. @code{par-map}
572returns a list comprising the return values from @var{proc}.
573@code{par-for-each} returns an unspecified value, but waits for all
574calls to complete.
575
576The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
577@var{elemN})}, where each @var{elem} is from the corresponding
578@var{lst}. Each @var{lst} must be the same length. The calls are
af1323c5 579made in parallel, each in its own thread.
07d83abe
MV
580
581These functions are like @code{map} and @code{for-each} (@pxref{List
582Mapping}), but make their @var{proc} calls in parallel.
583@end deffn
584
585@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
586@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
587Call @var{proc} on the elements of the given lists, in the same way as
588@code{par-map} and @code{par-for-each} above, but use no more than
af1323c5 589@var{n} threads at any one time. The order in which calls are
07d83abe
MV
590initiated within that threads limit is unspecified.
591
592These functions are good for controlling resource consumption if
593@var{proc} calls might be costly, or if there are many to be made. On
594a dual-CPU system for instance @math{@var{n}=4} might be enough to
595keep the CPUs utilized, and not consume too much memory.
596@end deffn
597
598@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
599Apply @var{pproc} to the elements of the given lists, and apply
600@var{sproc} to each result returned by @var{pproc}. The final return
601value is unspecified, but all calls will have been completed before
602returning.
603
604The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
605@var{elemN}))}, where each @var{elem} is from the corresponding
606@var{lst}. Each @var{lst} must have the same number of elements.
607
af1323c5
KR
608The @var{pproc} calls are made in parallel, in separate threads. No more
609than @var{n} threads are used at any one time. The order in which
07d83abe
MV
610@var{pproc} calls are initiated within that limit is unspecified.
611
612The @var{sproc} calls are made serially, in list element order, one at
613a time. @var{pproc} calls on later elements may execute in parallel
614with the @var{sproc} calls. Exactly which thread makes each
615@var{sproc} call is unspecified.
616
617This function is designed for individual calculations that can be done
618in parallel, but with results needing to be handled serially, for
619instance to write them to a file. The @var{n} limit on threads
620controls system resource usage when there are many calculations or
621when they might be costly.
622
623It will be seen that @code{n-for-each-par-map} is like a combination
624of @code{n-par-map} and @code{for-each},
625
626@example
af1323c5 627(for-each sproc (n-par-map n pproc lst1 ... lstN))
07d83abe
MV
628@end example
629
630@noindent
631But the actual implementation is more efficient since each @var{sproc}
632call, in turn, can be initiated once the relevant @var{pproc} call has
633completed, it doesn't need to wait for all to finish.
634@end deffn
635
636
b4fddbbe
MV
637@node Mutexes and Condition Variables
638@subsection Mutexes and Condition Variables
3cf066df 639@cindex mutex
b4fddbbe 640@cindex condition variable
3cf066df
KR
641
642A mutex is a thread synchronization object, it can be used by threads
643to control access to a shared resource. A mutex can be locked to
644indicate a resource is in use, and other threads can then block on the
645mutex to wait for the resource (or can just test and do something else
646if not available). ``Mutex'' is short for ``mutual exclusion''.
647
b4fddbbe
MV
648There are two types of mutexes in Guile, ``standard'' and
649``recursive''. They're created by @code{make-mutex} and
650@code{make-recursive-mutex} respectively, the operation functions are
651then common to both.
3cf066df
KR
652
653Note that for both types of mutex there's no protection against a
654``deadly embrace''. For instance if one thread has locked mutex A and
655is waiting on mutex B, but another thread owns B and is waiting on A,
656then an endless wait will occur (in the current implementation).
657Acquiring requisite mutexes in a fixed order (like always A before B)
658in all threads is one way to avoid such problems.
659
660@sp 1
661@deffn {Scheme Procedure} make-mutex
b4fddbbe
MV
662Return a new standard mutex. It is initially unlocked.
663@end deffn
3cf066df 664
b4fddbbe
MV
665@deffn {Scheme Procedure} make-recursive-mutex
666Return a new recursive mutex. It is initialloy unlocked.
3cf066df
KR
667@end deffn
668
669@deffn {Scheme Procedure} lock-mutex mutex
670Lock @var{mutex}. If the mutex is already locked by another thread
671then block and return only when @var{mutex} has been acquired.
672
b4fddbbe
MV
673For standard mutexes (@code{make-mutex}), and error is signalled if
674the thread has itself already locked @var{mutex}.
3cf066df 675
b4fddbbe
MV
676For a recursive mutex (@code{make-recursive-mutex}), if the thread has
677itself already locked @var{mutex}, then a further @code{lock-mutex}
678call increments the lock count. An additional @code{unlock-mutex}
679will be required to finally release.
3cf066df
KR
680
681When a system async (@pxref{System asyncs}) is activated for a thread
682blocked in @code{lock-mutex}, the wait is interrupted and the async is
b4fddbbe 683executed. When the async returns, the wait resumes.
3cf066df
KR
684@end deffn
685
b4fddbbe 686 @deffn {Scheme Procedure} try-mutex mutex
3cf066df
KR
687Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
688be acquired immediately then this is done and the return is @code{#t}.
689If @var{mutex} is locked by some other thread then nothing is done and
690the return is @code{#f}.
691@end deffn
692
693@deffn {Scheme Procedure} unlock-mutex mutex
b4fddbbe
MV
694Unlock @var{mutex}. An error is signalled if @var{mutex} is not
695locked by the calling thread.
696@end deffn
697
698@c begin (texi-doc-string "guile" "make-condition-variable")
699@deffn {Scheme Procedure} make-condition-variable
700Return a new condition variable.
701@end deffn
702
703@c begin (texi-doc-string "guile" "wait-condition-variable")
704@deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time]
705Wait until @var{cond-var} has been signalled. While waiting,
706@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
707is locked again when this function returns. When @var{time} is given,
708it specifies a point in time where the waiting should be aborted. It
709can be either a integer as returned by @code{current-time} or a pair
710as returned by @code{gettimeofday}. When the waiting is aborted,
711@code{#f} is returned. When the condition variable has in fact been
712signalled, @code{#t} is returned. The mutex is re-locked in any case
713before @code{wait-condition-variable} returns.
3cf066df 714
b4fddbbe
MV
715When a system async is activated for a thread that is blocked in a
716call to @code{wait-condition-variable}, the waiting is interrupted,
717the mutex is locked, and the async is executed. When the async
718returns, the mutex is unlocked again and the waiting is resumed. When
719the thread block while re-acquiring the mutex, execution of asyncs is
720blocked.
721@end deffn
3cf066df 722
b4fddbbe
MV
723@c begin (texi-doc-string "guile" "signal-condition-variable")
724@deffn {Scheme Procedure} signal-condition-variable cond-var
725Wake up one thread that is waiting for @var{cv}.
726@end deffn
727
728@c begin (texi-doc-string "guile" "broadcast-condition-variable")
729@deffn {Scheme Procedure} broadcast-condition-variable cond-var
730Wake up all threads that are waiting for @var{cv}.
3cf066df
KR
731@end deffn
732
733@sp 1
734The following are higher level operations on mutexes. These are
735available from
736
737@example
738(use-modules (ice-9 threads))
739@end example
740
741@deffn macro with-mutex mutex [body@dots{}]
742Lock @var{mutex}, evaluate the @var{body} forms, then unlock
743@var{mutex}. The return value is the return from the last @var{body}
744form.
745
746The lock, body and unlock form the branches of a @code{dynamic-wind}
747(@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
748error or new continuation exits @var{body}, and is re-locked if
749@var{body} is re-entered by a captured continuation.
750@end deffn
751
752@deffn macro monitor body@dots{}
753Evaluate the @var{body} forms, with a mutex locked so only one thread
754can execute that code at any one time. The return value is the return
755from the last @var{body} form.
756
757Each @code{monitor} form has its own private mutex and the locking and
758evaluation is as per @code{with-mutex} above. A standard mutex
759(@code{make-mutex}) is used, which means @var{body} must not
760recursively re-enter the @code{monitor} form.
761
762The term ``monitor'' comes from operating system theory, where it
763means a particular bit of code managing access to some resource and
764which only ever executes on behalf of one process at any one time.
765@end deffn
766
3cf066df 767
07d83abe
MV
768@c Local Variables:
769@c TeX-master: "guile.texi"
770@c End: