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