Core enhancements, by Julian Graham, to Guile's thread, mutex and
[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
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
12 plus the Cygnus programmer's manual; it should be *very* carefully
13 reviewed and largely reorganized.]
14
15 @menu
16 * Arbiters:: Synchronization primitives.
17 * Asyncs:: Asynchronous procedure invocation.
18 * Continuation Barriers:: Protection from non-local control flow.
19 * Threads:: Multiple threads of execution.
20 * Mutexes and Condition Variables:: Synchronization primitives.
21 * Blocking:: How to block properly in guile mode.
22 * Critical Sections:: Avoiding concurrency and reentries.
23 * Fluids and Dynamic States:: Thread-local variables, etc.
24 * Parallel Forms:: Parallel execution of forms.
25 @end menu
26
27
28 @node Arbiters
29 @subsection Arbiters
30 @cindex arbiters
31
32 Arbiters are synchronization objects, they can be used by threads to
33 control access to a shared resource. An arbiter can be locked to
34 indicate a resource is in use, and unlocked when done.
35
36 An arbiter is like a light-weight mutex (@pxref{Mutexes and Condition
37 Variables}). It uses less memory and may be faster, but there's no
38 way for a thread to block waiting on an arbiter, it can only test and
39 get the status returned.
40
41 @deffn {Scheme Procedure} make-arbiter name
42 @deffnx {C Function} scm_make_arbiter (name)
43 Return an object of type arbiter and name @var{name}. Its
44 state is initially unlocked. Arbiters are a way to achieve
45 process synchronization.
46 @end deffn
47
48 @deffn {Scheme Procedure} try-arbiter arb
49 @deffnx {C Function} scm_try_arbiter (arb)
50 @deffnx {C Function} scm_try_arbiter (arb)
51 If @var{arb} is unlocked, then lock it and return @code{#t}.
52 If @var{arb} is already locked, then do nothing and return
53 @code{#f}.
54 @end deffn
55
56 @deffn {Scheme Procedure} release-arbiter arb
57 @deffnx {C Function} scm_release_arbiter (arb)
58 If @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
61 Typical usage is for the thread which locked an arbiter to later
62 release it, but that's not required, any thread can release it.
63 @end deffn
64
65
66 @node Asyncs
67 @subsection Asyncs
68
69 @cindex asyncs
70 @cindex user asyncs
71 @cindex system asyncs
72
73 Asyncs are a means of deferring the excution of Scheme code until it is
74 safe to do so.
75
76 Guile provides two kinds of asyncs that share the basic concept but are
77 otherwise quite different: system asyncs and user asyncs. System asyncs
78 are integrated into the core of Guile and are executed automatically
79 when the system is in a state to allow the execution of Scheme code.
80 For example, it is not possible to execute Scheme code in a POSIX signal
81 handler, but such a signal handler can queue a system async to be
82 executed in the near future, when it is safe to do so.
83
84 System asyncs can also be queued for threads other than the current one.
85 This way, you can cause threads to asynchronously execute arbitrary
86 code.
87
88 User asyncs offer a convenient means of queueing procedures for future
89 execution and triggering this execution. They will not be executed
90 automatically.
91
92 @menu
93 * System asyncs::
94 * User asyncs::
95 @end menu
96
97 @node System asyncs
98 @subsubsection System asyncs
99
100 To cause the future asynchronous execution of a procedure in a given
101 thread, use @code{system-async-mark}.
102
103 Automatic invocation of system asyncs can be temporarily disabled by
104 calling @code{call-with-blocked-asyncs}. This function works by
105 temporarily increasing the @emph{async blocking level} of the current
106 thread while a given procedure is running. The blocking level starts
107 out at zero, and whenever a safe point is reached, a blocking level
108 greater than zero will prevent the execution of queued asyncs.
109
110 Analogously, the procedure @code{call-with-unblocked-asyncs} will
111 temporarily decrease the blocking level of the current thread. You
112 can use it when you want to disable asyncs by default and only allow
113 them temporarily.
114
115 In addition to the C versions of @code{call-with-blocked-asyncs} and
116 @code{call-with-unblocked-asyncs}, C code can use
117 @code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
118 inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
119 unblock system asyncs temporarily.
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)
124 Mark @var{proc} (a procedure with zero arguments) for future execution
125 in @var{thread}. When @var{proc} has already been marked for
126 @var{thread} but has not been executed yet, this call has no effect.
127 When @var{thread} is omitted, the thread that called
128 @code{system-async-mark} is used.
129
130 This procedure is not safe to be called from signal handlers. Use
131 @code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
132 signal 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
145 Call @var{proc} and block the execution of system asyncs by one level
146 for the current thread while it is running. Return the value returned
147 by @var{proc}. For the first two variants, call @var{proc} with no
148 arguments; 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
155 Call @var{proc} and unblock the execution of system asyncs by one
156 level for the current thread while it is running. Return the value
157 returned by @var{proc}. For the first two variants, call @var{proc}
158 with no arguments; for the third, call it with @var{data}.
159 @end deffn
160
161 @deftypefn {C Function} void scm_dynwind_block_asyncs ()
162 This function must be used inside a pair of calls to
163 @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
164 Wind}). During the dynwind context, asyncs are blocked by one level.
165 @end deftypefn
166
167 @deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
168 This function must be used inside a pair of calls to
169 @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
170 Wind}). During the dynwind context, asyncs are unblocked by one
171 level.
172 @end deftypefn
173
174 @node User asyncs
175 @subsubsection User asyncs
176
177 A user async is a pair of a thunk (a parameterless procedure) and a
178 mark. Setting the mark on a user async will cause the thunk to be
179 executed when the user async is passed to @code{run-asyncs}. Setting
180 the mark more than once is satisfied by one execution of the thunk.
181
182 User 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)
187 Create 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)
192 Mark 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)
197 Execute all thunks from the marked asyncs of the list @var{list_of_a}.
198 @end deffn
199
200 @node Continuation Barriers
201 @subsection Continuation Barriers
202
203 The non-local flow of control caused by continuations might sometimes
204 not be wanted. You can use @code{with-continuation-barrier} etc to
205 errect fences that continuations can not pass.
206
207 @deffn {Scheme Procedure} with-continuation-barrier proc
208 @deffnx {C Function} scm_with_continuation_barrier (proc)
209 Call @var{proc} and return its result. Do not allow the invocation of
210 continuations that would leave or enter the dynamic extent of the call
211 to @code{with-continuation-barrier}. Such an attempt causes an error
212 to be signaled.
213
214 Throws (such as errors) that are not caught from within @var{proc} are
215 caught by @code{with-continuation-barrier}. In that case, a short
216 message is printed to the current error port and @code{#f} is returned.
217
218 Thus, @code{with-continuation-barrier} returns exactly once.
219 @end deffn
220
221 @deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
222 Like @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
225
226 @node Threads
227 @subsection Threads
228 @cindex threads
229 @cindex Guile threads
230 @cindex POSIX threads
231
232 @deffn {Scheme Procedure} all-threads
233 @deffnx {C Function} scm_all_threads ()
234 Return a list of all threads.
235 @end deffn
236
237 @deffn {Scheme Procedure} current-thread
238 @deffnx {C Function} scm_current_thread ()
239 Return the thread that called this function.
240 @end deffn
241
242 @c begin (texi-doc-string "guile" "call-with-new-thread")
243 @deffn {Scheme Procedure} call-with-new-thread thunk [handler]
244 Call @code{thunk} in a new thread and with a new dynamic state,
245 returning the new thread. The procedure @var{thunk} is called via
246 @code{with-continuation-barrier}.
247
248 When @var{handler} is specified, then @var{thunk} is called from
249 within a @code{catch} with tag @code{#t} that has @var{handler} as its
250 handler. This catch is established inside the continuation barrier.
251
252 Once @var{thunk} or @var{handler} returns, the return value is made
253 the @emph{exit value} of the thread and the thread is terminated.
254 @end deffn
255
256 @deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
257 Call @var{body} in a new thread, passing it @var{body_data}, returning
258 the new thread. The function @var{body} is called via
259 @code{scm_c_with_continuation_barrier}.
260
261 When @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
264 catch is established inside the continuation barrier.
265
266 Once @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
270 @deffn {Scheme Procedure} thread? obj
271 @deffnx {C Function} scm_thread_p (obj)
272 Return @code{#t} iff @var{obj} is a thread; otherwise, return
273 @code{#f}.
274 @end deffn
275
276 @c begin (texi-doc-string "guile" "join-thread")
277 @deffn {Scheme Procedure} join-thread thread [timeout [timeoutval]]
278 @deffnx {C Function} scm_join_thread (thread)
279 @deffnx {C Function} scm_join_thread_timed (thread, timeout, timeoutval)
280 Wait for @var{thread} to terminate and return its exit value. Threads
281 that have not been created with @code{call-with-new-thread} or
282 @code{scm_spawn_thread} have an exit value of @code{#f}. When
283 @var{timeout} is given, it specifies a point in time where the waiting
284 should be aborted. It can be either an integer as returned by
285 @code{current-time} or a pair as returned by @code{gettimeofday}.
286 When the waiting is aborted, @var{timeoutval} is returned (if it is
287 specified; @code{#f} is returned otherwise).
288 @end deffn
289
290 @deffn {Scheme Procedure} thread-exited? thread
291 @deffnx {C Function} scm_thread_exited_p (thread)
292 Return @code{#t} iff @var{thread} has exited.
293 @end deffn
294
295 @c begin (texi-doc-string "guile" "yield")
296 @deffn {Scheme Procedure} yield
297 If one or more threads are waiting to execute, calling yield forces an
298 immediate context switch to one of them. Otherwise, yield has no effect.
299 @end deffn
300
301 @deffn {Scheme Procedure} cancel-thread thread
302 @deffnx {C Function} scm_cancel_thread (thread)
303 Asynchronously notify @var{thread} to exit. Immediately after
304 receiving this notification, @var{thread} will call its cleanup handler
305 (if one has been set) and then terminate, aborting any evaluation that
306 is in progress.
307
308 Because Guile threads are isomorphic with POSIX threads, @var{thread}
309 will not receive its cancellation signal until it reaches a cancellation
310 point. See your operating system's POSIX threading documentation for
311 more information on cancellation points; note that in Guile, unlike
312 native POSIX threads, a thread can receive a cancellation notification
313 while attempting to lock a mutex.
314 @end deffn
315
316 @deffn {Scheme Procedure} set-thread-cleanup! thread proc
317 @deffnx {C Function} scm_set_thread_cleanup_x (thread, proc)
318 Set @var{proc} as the cleanup handler for the thread @var{thread}.
319 @var{proc}, which must be a thunk, will be called when @var{thread}
320 exits, either normally or by being canceled. Thread cleanup handlers
321 can be used to perform useful tasks like releasing resources, such as
322 locked mutexes, when thread exit cannot be predicted.
323
324 The return value of @var{proc} will be set as the @emph{exit value} of
325 @var{thread}.
326
327 To remove a cleanup handler, pass @code{#f} for @var{proc}.
328 @end deffn
329
330 @deffn {Scheme Procedure} thread-cleanup thread
331 @deffnx {C Function} scm_thread_cleanup (thread)
332 Return the cleanup handler currently installed for the thread
333 @var{thread}. If no cleanup handler is currently installed,
334 thread-cleanup returns @code{#f}.
335 @end deffn
336
337 Higher level thread procedures are available by loading the
338 @code{(ice-9 threads)} module. These provide standardized
339 thread creation.
340
341 @deffn macro make-thread proc [args@dots{}]
342 Apply @var{proc} to @var{args} in a new thread formed by
343 @code{call-with-new-thread} using a default error handler that display
344 the error to the current error port. The @var{args@dots{}}
345 expressions are evaluated in the new thread.
346 @end deffn
347
348 @deffn macro begin-thread first [rest@dots{}]
349 Evaluate forms @var{first} and @var{rest} in a new thread formed by
350 @code{call-with-new-thread} using a default error handler that display
351 the error to the current error port.
352 @end deffn
353
354 @node Mutexes and Condition Variables
355 @subsection Mutexes and Condition Variables
356 @cindex mutex
357 @cindex condition variable
358
359 A mutex is a thread synchronization object, it can be used by threads
360 to control access to a shared resource. A mutex can be locked to
361 indicate a resource is in use, and other threads can then block on the
362 mutex to wait for the resource (or can just test and do something else
363 if not available). ``Mutex'' is short for ``mutual exclusion''.
364
365 There are two types of mutexes in Guile, ``standard'' and
366 ``recursive''. They're created by @code{make-mutex} and
367 @code{make-recursive-mutex} respectively, the operation functions are
368 then common to both.
369
370 Note that for both types of mutex there's no protection against a
371 ``deadly embrace''. For instance if one thread has locked mutex A and
372 is waiting on mutex B, but another thread owns B and is waiting on A,
373 then an endless wait will occur (in the current implementation).
374 Acquiring requisite mutexes in a fixed order (like always A before B)
375 in all threads is one way to avoid such problems.
376
377 @sp 1
378 @deffn {Scheme Procedure} make-mutex . flags
379 @deffnx {C Function} scm_make_mutex ()
380 @deffnx {C Function} scm_make_mutex_with_flags (SCM flag)
381 Return a new mutex. It is initially unlocked. If @var{flags} is
382 specified, it must be a list of symbols specifying configuration flags
383 for the newly-created mutex. The supported flags are:
384 @table @code
385 @item unchecked-unlock
386 Unless this flag is present, a call to `unlock-mutex' on the returned
387 mutex when it is already unlocked will cause an error to be signalled.
388
389 @item allow-external-unlock
390 Allow the returned mutex to be unlocked by the calling thread even if
391 it was originally locked by a different thread.
392
393 @item recursive
394 The returned mutex will be recursive.
395
396 @end table
397 @end deffn
398
399 @deffn {Scheme Procedure} mutex? obj
400 @deffnx {C Function} scm_mutex_p (obj)
401 Return @code{#t} iff @var{obj} is a mutex; otherwise, return
402 @code{#f}.
403 @end deffn
404
405 @deffn {Scheme Procedure} make-recursive-mutex
406 @deffnx {C Function} scm_make_recursive_mutex ()
407 Create a new recursive mutex. It is initially unlocked. Calling this
408 function is equivalent to calling `make-mutex' and specifying the
409 @code{recursive} flag.
410 @end deffn
411
412 @deffn {Scheme Procedure} lock-mutex mutex [timeout]
413 @deffnx {C Function} scm_lock_mutex (mutex)
414 @deffnx {C Function} scm_lock_mutex_timed (mutex, timeout)
415 Lock @var{mutex}. If the mutex is already locked by another thread
416 then block and return only when @var{mutex} has been acquired.
417
418 When @var{timeout} is given, it specifies a point in time where the
419 waiting should be aborted. It can be either an integer as returned
420 by @code{current-time} or a pair as returned by @code{gettimeofday}.
421 When the waiting is aborted, @code{#f} is returned.
422
423 For standard mutexes (@code{make-mutex}), and error is signalled if
424 the thread has itself already locked @var{mutex}.
425
426 For a recursive mutex (@code{make-recursive-mutex}), if the thread has
427 itself already locked @var{mutex}, then a further @code{lock-mutex}
428 call increments the lock count. An additional @code{unlock-mutex}
429 will be required to finally release.
430
431 If @var{mutex} was locked by a thread that exited before unlocking it,
432 the next attempt to lock @var{mutex} will succeed, but
433 @code{abandoned-mutex-error} will be signalled.
434
435 When a system async (@pxref{System asyncs}) is activated for a thread
436 blocked in @code{lock-mutex}, the wait is interrupted and the async is
437 executed. When the async returns, the wait resumes.
438 @end deffn
439
440 @deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
441 Arrange for @var{mutex} to be locked whenever the current dynwind
442 context is entered and to be unlocked when it is exited.
443 @end deftypefn
444
445 @deffn {Scheme Procedure} try-mutex mx
446 @deffnx {C Function} scm_try_mutex (mx)
447 Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
448 be acquired immediately then this is done and the return is @code{#t}.
449 If @var{mutex} is locked by some other thread then nothing is done and
450 the return is @code{#f}.
451 @end deffn
452
453 @deffn {Scheme Procedure} unlock-mutex mutex [condvar [timeout]]
454 @deffnx {C Function} scm_unlock_mutex (mutex)
455 @deffnx {C Function} scm_unlock_mutex_timed (mutex, condvar, timeout)
456 Unlock @var{mutex}. An error is signalled if @var{mutex} is not locked
457 and was not created with the @code{unchecked-unlock} flag set, or if
458 @var{mutex} is locked by a thread other than the calling thread and was
459 not created with the @code{allow-external-unlock} flag set.
460
461 If @var{condvar} is given, it specifies a condition variable upon
462 which the calling thread will wait to be signalled before returning.
463 (This behavior is very similar to that of
464 @code{wait-condition-variable}, except that the mutex is left in an
465 unlocked state when the function returns.)
466
467 When @var{timeout} is also given, it specifies a point in time where
468 the waiting should be aborted. It can be either an integer as
469 returned by @code{current-time} or a pair as returned by
470 @code{gettimeofday}. When the waiting is aborted, @code{#f} is
471 returned. Otherwise the function returns @code{#t}.
472 @end deffn
473
474 @deffn {Scheme Procedure} make-condition-variable
475 @deffnx {C Function} scm_make_condition_variable ()
476 Return a new condition variable.
477 @end deffn
478
479 @deffn {Scheme Procedure} condition-variable? obj
480 @deffnx {C Function} scm_condition_variable_p (obj)
481 Return @code{#t} iff @var{obj} is a condition variable; otherwise,
482 return @code{#f}.
483 @end deffn
484
485 @deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
486 @deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
487 Wait until @var{condvar} has been signalled. While waiting,
488 @var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
489 is locked again when this function returns. When @var{time} is given,
490 it specifies a point in time where the waiting should be aborted. It
491 can be either a integer as returned by @code{current-time} or a pair
492 as returned by @code{gettimeofday}. When the waiting is aborted,
493 @code{#f} is returned. When the condition variable has in fact been
494 signalled, @code{#t} is returned. The mutex is re-locked in any case
495 before @code{wait-condition-variable} returns.
496
497 When a system async is activated for a thread that is blocked in a
498 call to @code{wait-condition-variable}, the waiting is interrupted,
499 the mutex is locked, and the async is executed. When the async
500 returns, the mutex is unlocked again and the waiting is resumed. When
501 the thread block while re-acquiring the mutex, execution of asyncs is
502 blocked.
503 @end deffn
504
505 @deffn {Scheme Procedure} signal-condition-variable condvar
506 @deffnx {C Function} scm_signal_condition_variable (condvar)
507 Wake up one thread that is waiting for @var{condvar}.
508 @end deffn
509
510 @deffn {Scheme Procedure} broadcast-condition-variable condvar
511 @deffnx {C Function} scm_broadcast_condition_variable (condvar)
512 Wake up all threads that are waiting for @var{condvar}.
513 @end deffn
514
515 @sp 1
516 The following are higher level operations on mutexes. These are
517 available from
518
519 @example
520 (use-modules (ice-9 threads))
521 @end example
522
523 @deffn macro with-mutex mutex [body@dots{}]
524 Lock @var{mutex}, evaluate the @var{body} forms, then unlock
525 @var{mutex}. The return value is the return from the last @var{body}
526 form.
527
528 The lock, body and unlock form the branches of a @code{dynamic-wind}
529 (@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
530 error or new continuation exits @var{body}, and is re-locked if
531 @var{body} is re-entered by a captured continuation.
532 @end deffn
533
534 @deffn macro monitor body@dots{}
535 Evaluate the @var{body} forms, with a mutex locked so only one thread
536 can execute that code at any one time. The return value is the return
537 from the last @var{body} form.
538
539 Each @code{monitor} form has its own private mutex and the locking and
540 evaluation is as per @code{with-mutex} above. A standard mutex
541 (@code{make-mutex}) is used, which means @var{body} must not
542 recursively re-enter the @code{monitor} form.
543
544 The term ``monitor'' comes from operating system theory, where it
545 means a particular bit of code managing access to some resource and
546 which only ever executes on behalf of one process at any one time.
547 @end deffn
548
549
550 @node Blocking
551 @subsection Blocking in Guile Mode
552
553 A thread must not block outside of a libguile function while it is in
554 guile mode. The following functions can be used to temporily leave
555 guile mode or to perform some common blocking operations in a supported
556 way.
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 @c @node Futures
795 @c @subsection Futures
796 @c @cindex futures
797
798 @c -- Futures are disabled for the time being, see futures.h for an
799 @c -- explanation.
800
801 @c Futures are a convenient way to run a calculation in a new thread, and
802 @c only wait for the result when it's actually needed.
803
804 @c Futures are similar to promises (@pxref{Delayed Evaluation}), in that
805 @c they allow mainline code to continue immediately. But @code{delay}
806 @c doesn't evaluate at all until forced, whereas @code{future} starts
807 @c immediately in a new thread.
808
809 @c @deffn {syntax} future expr
810 @c Begin evaluating @var{expr} in a new thread, and return a ``future''
811 @c object representing the calculation.
812 @c @end deffn
813
814 @c @deffn {Scheme Procedure} make-future thunk
815 @c @deffnx {C Function} scm_make_future (thunk)
816 @c Begin evaluating the call @code{(@var{thunk})} in a new thread, and
817 @c return a ``future'' object representing the calculation.
818 @c @end deffn
819
820 @c @deffn {Scheme Procedure} future-ref f
821 @c @deffnx {C Function} scm_future_ref (f)
822 @c Return the value computed by the future @var{f}. If @var{f} has not
823 @c yet finished executing then wait for it to do so.
824 @c @end deffn
825
826
827 @node Parallel Forms
828 @subsection Parallel forms
829 @cindex parallel forms
830
831 The functions described in this section are available from
832
833 @example
834 (use-modules (ice-9 threads))
835 @end example
836
837 @deffn syntax parallel expr1 @dots{} exprN
838 Evaluate each @var{expr} expression in parallel, each in its own thread.
839 Return the results as a set of @var{N} multiple values
840 (@pxref{Multiple Values}).
841 @end deffn
842
843 @deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
844 Evaluate each @var{expr} in parallel, each in its own thread, then bind
845 the results to the corresponding @var{var} variables and evaluate
846 @var{body}.
847
848 @code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
849 expressions for the bindings are evaluated in parallel.
850 @end deffn
851
852 @deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
853 @deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
854 Call @var{proc} on the elements of the given lists. @code{par-map}
855 returns a list comprising the return values from @var{proc}.
856 @code{par-for-each} returns an unspecified value, but waits for all
857 calls to complete.
858
859 The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
860 @var{elemN})}, where each @var{elem} is from the corresponding
861 @var{lst}. Each @var{lst} must be the same length. The calls are
862 made in parallel, each in its own thread.
863
864 These functions are like @code{map} and @code{for-each} (@pxref{List
865 Mapping}), but make their @var{proc} calls in parallel.
866 @end deffn
867
868 @deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
869 @deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
870 Call @var{proc} on the elements of the given lists, in the same way as
871 @code{par-map} and @code{par-for-each} above, but use no more than
872 @var{n} threads at any one time. The order in which calls are
873 initiated within that threads limit is unspecified.
874
875 These functions are good for controlling resource consumption if
876 @var{proc} calls might be costly, or if there are many to be made. On
877 a dual-CPU system for instance @math{@var{n}=4} might be enough to
878 keep the CPUs utilized, and not consume too much memory.
879 @end deffn
880
881 @deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
882 Apply @var{pproc} to the elements of the given lists, and apply
883 @var{sproc} to each result returned by @var{pproc}. The final return
884 value is unspecified, but all calls will have been completed before
885 returning.
886
887 The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
888 @var{elemN}))}, where each @var{elem} is from the corresponding
889 @var{lst}. Each @var{lst} must have the same number of elements.
890
891 The @var{pproc} calls are made in parallel, in separate threads. No more
892 than @var{n} threads are used at any one time. The order in which
893 @var{pproc} calls are initiated within that limit is unspecified.
894
895 The @var{sproc} calls are made serially, in list element order, one at
896 a time. @var{pproc} calls on later elements may execute in parallel
897 with the @var{sproc} calls. Exactly which thread makes each
898 @var{sproc} call is unspecified.
899
900 This function is designed for individual calculations that can be done
901 in parallel, but with results needing to be handled serially, for
902 instance to write them to a file. The @var{n} limit on threads
903 controls system resource usage when there are many calculations or
904 when they might be costly.
905
906 It will be seen that @code{n-for-each-par-map} is like a combination
907 of @code{n-par-map} and @code{for-each},
908
909 @example
910 (for-each sproc (n-par-map n pproc lst1 ... lstN))
911 @end example
912
913 @noindent
914 But the actual implementation is more efficient since each @var{sproc}
915 call, in turn, can be initiated once the relevant @var{pproc} call has
916 completed, it doesn't need to wait for all to finish.
917 @end deffn
918
919
920
921 @c Local Variables:
922 @c TeX-master: "guile.texi"
923 @c End: