See ChangeLog from 2005-03-02.
[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.
18* Dynamic Roots:: Root frames of execution.
19* Threads:: Multiple threads of execution.
20* Fluids:: Thread-local variables.
21* Futures:: Delayed execution in new threads.
22* Parallel Forms:: Parallel execution of forms.
3cf066df 23* Mutexes:: Synchronization primitives.
07d83abe
MV
24@end menu
25
26
27@node Arbiters
28@subsection Arbiters
07d83abe
MV
29@cindex arbiters
30
e136aab0
KR
31Arbiters are synchronization objects, they can be used by threads to
32control access to a shared resource. An arbiter can be locked to
33indicate a resource is in use, and unlocked when done.
07d83abe 34
3cf066df
KR
35An arbiter is like a light-weight mutex (@pxref{Mutexes}). It uses
36less memory and may be faster, but there's no way for a thread to
37block waiting on an arbiter, it can only test and get the status
38returned.
07d83abe
MV
39
40@deffn {Scheme Procedure} make-arbiter name
41@deffnx {C Function} scm_make_arbiter (name)
cdf1ad3b
MV
42Return an object of type arbiter and name @var{name}. Its
43state is initially unlocked. Arbiters are a way to achieve
44process synchronization.
07d83abe
MV
45@end deffn
46
47@deffn {Scheme Procedure} try-arbiter arb
48@deffnx {C Function} scm_try_arbiter (arb)
cdf1ad3b
MV
49@deffnx {C Function} scm_try_arbiter (arb)
50If @var{arb} is unlocked, then lock it and return @code{#t}.
51If @var{arb} is already locked, then do nothing and return
52@code{#f}.
07d83abe
MV
53@end deffn
54
55@deffn {Scheme Procedure} release-arbiter arb
56@deffnx {C Function} scm_release_arbiter (arb)
e136aab0
KR
57If @var{arb} is locked, then unlock it and return @code{#t}. If
58@var{arb} is already unlocked, then do nothing and return @code{#f}.
59
60Typical usage is for the thread which locked an arbiter to later
61release it, but that's not required, any thread can release it.
07d83abe
MV
62@end deffn
63
64
65@node Asyncs
66@subsection Asyncs
67
68@cindex asyncs
69@cindex user asyncs
70@cindex system asyncs
71
72Asyncs are a means of deferring the excution of Scheme code until it is
73safe to do so.
74
75Guile provides two kinds of asyncs that share the basic concept but are
76otherwise quite different: system asyncs and user asyncs. System asyncs
77are integrated into the core of Guile and are executed automatically
78when the system is in a state to allow the execution of Scheme code.
79For example, it is not possible to execute Scheme code in a POSIX signal
80handler, but such a signal handler can queue a system async to be
81executed in the near future, when it is safe to do so.
82
83System asyncs can also be queued for threads other than the current one.
84This way, you can cause threads to asynchronously execute arbitrary
85code.
86
87User asyncs offer a convenient means of queueing procedures for future
88execution and triggering this execution. They will not be executed
89automatically.
90
91@menu
92* System asyncs::
93* User asyncs::
94@end menu
95
96@node System asyncs
97@subsubsection System asyncs
98
99To cause the future asynchronous execution of a procedure in a given
100thread, use @code{system-async-mark}.
101
102Automatic invocation of system asyncs can be temporarily disabled by
103calling @code{call-with-blocked-asyncs}. This function works by
104temporarily increasing the @emph{async blocking level} of the current
105thread while a given procedure is running. The blocking level starts
106out at zero, and whenever a safe point is reached, a blocking level
107greater than zero will prevent the execution of queued asyncs.
108
109Analogously, the procedure @code{call-with-unblocked-asyncs} will
110temporarily decrease the blocking level of the current thread. You
111can use it when you want to disable asyncs by default and only allow
112them temporarily.
113
114In addition to the C versions of @code{call-with-blocked-asyncs} and
115@code{call-with-unblocked-asyncs}, C code can use
76da80e7 116@code{scm_with_blocked_asyncs} and @code{scm_with_unblocked_asyncs}
07d83abe
MV
117inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs
118temporarily.
119
120@deffn {Scheme Procedure} system-async-mark proc [thread]
121@deffnx {C Function} scm_system_async_mark (proc)
122@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
123Mark @var{proc} (a procedure with zero arguments) for future execution
124in @var{thread}. When @var{proc} has already been marked for
125@var{thread} but has not been executed yet, this call has no effect.
126When @var{thread} is omitted, the thread that called
127@code{system-async-mark} is used.
128
129This procedure is not safe to be called from signal handlers. Use
130@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
131signal handlers.
132@end deffn
133
134@c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
135@c scm_c_call_with_unblocked_asyncs puts "void" into the function
136@c index. Would prefer to use @deftypefnx if makeinfo allowed that,
137@c or a @deftypefn with an empty return type argument if it didn't
138@c introduce an extra space.
139
140@deffn {Scheme Procedure} call-with-blocked-asyncs proc
141@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
142@deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
143@findex scm_c_call_with_blocked_asyncs
144Call @var{proc} and block the execution of system asyncs by one level
145for the current thread while it is running. Return the value returned
146by @var{proc}. For the first two variants, call @var{proc} with no
147arguments; for the third, call it with @var{data}.
148@end deffn
149
150@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
151@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
152@deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
153@findex scm_c_call_with_unblocked_asyncs
154Call @var{proc} and unblock the execution of system asyncs by one
155level for the current thread while it is running. Return the value
156returned by @var{proc}. For the first two variants, call @var{proc}
157with no arguments; for the third, call it with @var{data}.
158@end deffn
159
160@deftypefn {C Function} void scm_frame_block_asyncs ()
161This function must be used inside a pair of calls to
162@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
163During the dynamic extent of the frame, asyncs are blocked by one level.
164@end deftypefn
165
166@deftypefn {C Function} void scm_frame_unblock_asyncs ()
167This function must be used inside a pair of calls to
168@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
169During the dynamic extent of the frame, asyncs are unblocked by one
170level.
171@end deftypefn
172
173@node User asyncs
174@subsubsection User asyncs
175
176A user async is a pair of a thunk (a parameterless procedure) and a
177mark. Setting the mark on a user async will cause the thunk to be
178executed when the user async is passed to @code{run-asyncs}. Setting
179the mark more than once is satisfied by one execution of the thunk.
180
181User asyncs are created with @code{async}. They are marked with
182@code{async-mark}.
183
184@deffn {Scheme Procedure} async thunk
185@deffnx {C Function} scm_async (thunk)
186Create a new user async for the procedure @var{thunk}.
187@end deffn
188
189@deffn {Scheme Procedure} async-mark a
190@deffnx {C Function} scm_async_mark (a)
191Mark the user async @var{a} for future execution.
192@end deffn
193
194@deffn {Scheme Procedure} run-asyncs list_of_a
195@deffnx {C Function} scm_run_asyncs (list_of_a)
196Execute all thunks from the marked asyncs of the list @var{list_of_a}.
197@end deffn
198
199
200@node Dynamic Roots
201@subsection Dynamic Roots
202@cindex dynamic roots
203
204A @dfn{dynamic root} is a root frame of Scheme evaluation.
205The top-level repl, for example, is an instance of a dynamic root.
206
207Each dynamic root has its own chain of dynamic-wind information. Each
208has its own set of continuations, jump-buffers, and pending CATCH
209statements which are inaccessible from the dynamic scope of any
210other dynamic root.
211
212In a thread-based system, each thread has its own dynamic root. Therefore,
213continuations created by one thread may not be invoked by another.
214
215Even in a single-threaded system, it is sometimes useful to create a new
216dynamic root. For example, if you want to apply a procedure, but to
217not allow that procedure to capture the current continuation, calling
218the procedure under a new dynamic root will do the job.
219
220@deffn {Scheme Procedure} call-with-dynamic-root thunk handler
221@deffnx {C Function} scm_call_with_dynamic_root (thunk, handler)
222Evaluate @code{(thunk)} in a new dynamic context, returning its value.
223
224If an error occurs during evaluation, apply @var{handler} to the
225arguments to the throw, just as @code{throw} would. If this happens,
226@var{handler} is called outside the scope of the new root -- it is
227called in the same dynamic context in which
228@code{call-with-dynamic-root} was evaluated.
229
230If @var{thunk} captures a continuation, the continuation is rooted at
231the call to @var{thunk}. In particular, the call to
232@code{call-with-dynamic-root} is not captured. Therefore,
233@code{call-with-dynamic-root} always returns at most one time.
234
235Before calling @var{thunk}, the dynamic-wind chain is un-wound back to
236the root and a new chain started for @var{thunk}. Therefore, this call
237may not do what you expect:
238
239@lisp
240;; Almost certainly a bug:
241(with-output-to-port
242 some-port
243
244 (lambda ()
245 (call-with-dynamic-root
246 (lambda ()
247 (display 'fnord)
248 (newline))
249 (lambda (errcode) errcode))))
250@end lisp
251
252The problem is, on what port will @samp{fnord} be displayed? You
253might expect that because of the @code{with-output-to-port} that
254it will be displayed on the port bound to @code{some-port}. But it
255probably won't -- before evaluating the thunk, dynamic winds are
256unwound, including those created by @code{with-output-to-port}.
257So, the standard output port will have been re-set to its default value
258before @code{display} is evaluated.
259
260(This function was added to Guile mostly to help calls to functions in C
261libraries that can not tolerate non-local exits or calls that return
262multiple times. If such functions call back to the interpreter, it should
263be under a new dynamic root.)
264@end deffn
265
266
267@deffn {Scheme Procedure} dynamic-root
268@deffnx {C Function} scm_dynamic_root ()
269Return an object representing the current dynamic root.
270
271These objects are only useful for comparison using @code{eq?}.
272They are currently represented as numbers, but your code should
273in no way depend on this.
274@end deffn
275
276@c begin (scm-doc-string "boot-9.scm" "quit")
277@deffn {Scheme Procedure} quit [exit_val]
278Throw back to the error handler of the current dynamic root.
279
280If integer @var{exit_val} is specified and if Guile is being used
281stand-alone and if quit is called from the initial dynamic-root,
282@var{exit_val} becomes the exit status of the Guile process and the
283process exits.
284@end deffn
285
286When Guile is run interactively, errors are caught from within the
287read-eval-print loop. An error message will be printed and @code{abort}
288called. A default set of signal handlers is installed, e.g., to allow
289user interrupt of the interpreter.
290
291It is possible to switch to a "batch mode", in which the interpreter
292will terminate after an error and in which all signals cause their
293default actions. Switching to batch mode causes any handlers installed
294from Scheme code to be removed. An example of where this is useful is
295after forking a new process intended to run non-interactively.
296
297@c begin (scm-doc-string "boot-9.scm" "batch-mode?")
298@deffn {Scheme Procedure} batch-mode?
299Returns a boolean indicating whether the interpreter is in batch mode.
300@end deffn
301
302@c begin (scm-doc-string "boot-9.scm" "set-batch-mode?!")
303@deffn {Scheme Procedure} set-batch-mode?! arg
304If @var{arg} is true, switches the interpreter to batch mode.
305The @code{#f} case has not been implemented.
306@end deffn
307
308@node Threads
309@subsection Threads
310@cindex threads
311@cindex Guile threads
312@cindex POSIX threads
313
314Guile threads are implemented using POSIX threads, they run
315pre-emptively and concurrently through both Scheme code and system
316calls. The only exception is for garbage collection, where all
317threads must rendezvous.
318
319@menu
320* Low level thread primitives::
321* Higher level thread procedures::
322* C level thread interface::
323@end menu
324
325
326@node Low level thread primitives
327@subsubsection Low level thread primitives
328
cdf1ad3b
MV
329@deffn {Scheme Procedure} all-threads
330@deffnx {C Function} scm_all_threads ()
331Return a list of all threads.
332@end deffn
333
334@deffn {Scheme Procedure} current-thread
335@deffnx {C Function} scm_current_thread ()
336Return the thread that called this function.
337@end deffn
07d83abe
MV
338
339@c begin (texi-doc-string "guile" "call-with-new-thread")
340@deffn {Scheme Procedure} call-with-new-thread thunk error-handler
341Evaluate @code{(thunk)} in a new thread, and new dynamic context,
342returning a new thread object representing the thread.
343
344If an error occurs during evaluation, call error-handler, passing it
345an error code. If this happens, the error-handler is called outside
346the scope of the new root -- it is called in the same dynamic context
347in which with-new-thread was evaluated, but not in the caller's
348thread.
349
350All the evaluation rules for dynamic roots apply to threads.
351@end deffn
352
353@c begin (texi-doc-string "guile" "join-thread")
354@deffn {Scheme Procedure} join-thread thread
355Suspend execution of the calling thread until the target @var{thread}
356terminates, unless the target @var{thread} has already terminated.
357@end deffn
358
cdf1ad3b
MV
359@deffn {Scheme Procedure} thread-exited? thread
360@deffnx {C Function} scm_thread_exited_p (thread)
361Return @code{#t} iff @var{thread} has exited.
362@end deffn
363
07d83abe
MV
364@c begin (texi-doc-string "guile" "yield")
365@deffn {Scheme Procedure} yield
366If one or more threads are waiting to execute, calling yield forces an
367immediate context switch to one of them. Otherwise, yield has no effect.
368@end deffn
369
07d83abe
MV
370@c begin (texi-doc-string "guile" "make-condition-variable")
371@deffn {Scheme Procedure} make-condition-variable
372Make a new condition variable.
373@end deffn
374
cdf1ad3b
MV
375@deffn {Scheme Procedure} make-fair-condition-variable
376@deffnx {C Function} scm_make_fair_condition_variable ()
377Make a new fair condition variable.
378@end deffn
379
07d83abe
MV
380@c begin (texi-doc-string "guile" "wait-condition-variable")
381@deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time]
382Wait until @var{cond-var} has been signalled. While waiting,
383@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
384is locked again when this function returns. When @var{time} is given,
385it specifies a point in time where the waiting should be aborted. It
386can be either a integer as returned by @code{current-time} or a pair
387as returned by @code{gettimeofday}. When the waiting is aborted,
388@code{#f} is returned. When the condition variable has in fact been
389signalled, @code{#t} is returned. The mutex is re-locked in any case
390before @code{wait-condition-variable} returns.
391
392When a system async is activated for a thread that is blocked in a
393call to @code{wait-condition-variable}, the waiting is interrupted,
394the mutex is locked, and the async is executed. When the async
395returns, the mutex is unlocked again and the waiting is resumed.
396@end deffn
397
398@c begin (texi-doc-string "guile" "signal-condition-variable")
399@deffn {Scheme Procedure} signal-condition-variable cond-var
400Wake up one thread that is waiting for @var{cv}.
401@end deffn
402
403@c begin (texi-doc-string "guile" "broadcast-condition-variable")
404@deffn {Scheme Procedure} broadcast-condition-variable cond-var
405Wake up all threads that are waiting for @var{cv}.
406@end deffn
407
408@node Higher level thread procedures
409@subsubsection Higher level thread procedures
410
411@c new by ttn, needs review
412
413Higher level thread procedures are available by loading the
414@code{(ice-9 threads)} module. These provide standardized
3cf066df 415thread creation.
07d83abe
MV
416
417@deffn macro make-thread proc [args@dots{}]
418Apply @var{proc} to @var{args} in a new thread formed by
419@code{call-with-new-thread} using a default error handler that display
420the error to the current error port.
421@end deffn
422
423@deffn macro begin-thread first [rest@dots{}]
424Evaluate forms @var{first} and @var{rest} in a new thread formed by
425@code{call-with-new-thread} using a default error handler that display
426the error to the current error port.
427@end deffn
428
07d83abe
MV
429@node C level thread interface
430@subsubsection C level thread interface
431
3cf066df
KR
432You can create and manage threads
433with the C versions of the primitives above.
434These
07d83abe
MV
435functions and data types are only available from C and can not be
436mixed with the first set from above. However, they might be more
437efficient and can be used in situations where Scheme data types are
438not allowed or are inconvenient to use.
439
440Furthermore, they are the primitives that Guile relies on for its own
441higher level threads. By reimplementing them, you can adapt Guile to
442different low-level thread implementations.
443
444C code in a thread must call a libguile function periodically. When
445one thread finds garbage collection is required, it waits for all
446threads to rendezvous before doing that GC. Such a rendezvous is
447checked within libguile functions. If C code wants to sleep or block
448in a thread it should use one of the libguile functions provided.
449
450Only threads created by Guile can use the libguile functions. Threads
451created directly with say @code{pthread_create} are unknown to Guile
452and they cannot call libguile. The stack in such foreign threads is
453not scanned during GC, so @code{SCM} values generally cannot be held
454there.
455
456@c FIXME:
457@c
458@c Describe SCM_TICK which can be called if no other libguile
459@c function is being used by a C function.
460@c
461@c Describe "Guile mode", which a thread can enter and exit. There
462@c are no functions for doing this yet.
463@c
464@c When in guile mode a thread can call libguile, is subject to the
465@c tick rule, and its stack is scanned. When not in guile mode it
466@c cannot call libguile, it doesn't have to tick, and its stack is
467@c not scanned. The strange guile control flow things like
468@c exceptions, continuations and asyncs only occur when in guile
469@c mode.
470@c
471@c When guile mode is exited, the portion of the stack allocated
472@c while it was in guile mode is still scanned. This portion may not
473@c be modified when outside guile mode. The stack ends up
474@c partitioned into alternating guile and non-guile regions.
475@c
476@c Leaving guile mode is convenient when running an extended
477@c calculation not involving guile, since one doesn't need to worry
478@c about SCM_TICK calls.
479
480
481@deftp {C Data Type} scm_t_thread
482This data type represents a thread, to be used with scm_thread_create,
483etc.
484@end deftp
485
486@deftypefn {C Function} int scm_thread_create (scm_t_thread *t, void (*proc)(void *), void *data)
487Create a new thread that will start by calling @var{proc}, passing it
488@var{data}. A handle for the new thread is stored in @var{t}, which
489must be non-NULL. The thread terminated when @var{proc} returns.
490When the thread has not been detached, its handle remains valid after
491is has terminated so that it can be used with @var{scm_thread_join},
492for example. When it has been detached, the handle becomes invalid as
493soon as the thread terminates.
494@end deftypefn
495
496@deftypefn {C Function} void scm_thread_detach (scm_t_thread t)
497Detach the thread @var{t}. See @code{scm_thread_create}.
498@end deftypefn
499
500@deftypefn {C Function} void scm_thread_join (scm_t_thread t)
501Wait for thread @var{t} to terminate. The thread must not have been
502detached at the time that @code{scm_thread_join} is called, but it
503might have been detached by the time it terminates.
504@end deftypefn
505
506@deftypefn {C Function} scm_t_thread scm_thread_self ()
507Return the handle of the calling thread.
508@end deftypefn
509
07d83abe
MV
510@deftp {C Data Type} scm_t_cond
511This data type represents a condition variable, to be used with
512scm_cond_init, etc.
513@end deftp
514
515@deftypefn {C Function} void scm_cond_init (scm_t_cond *c)
3cf066df 516Initialize the condition variable structure pointed to by @var{c}.
07d83abe
MV
517@end deftypefn
518
519@deftypefn {C Function} void scm_cond_destroy (scm_t_cond *c)
520Deallocate all resources associated with @var{c}.
521@end deftypefn
522
523@deftypefn {C Function} void scm_cond_wait (scm_t_cond *c, scm_t_mutex *m)
524Wait for @var{c} to be signalled. While waiting @var{m} is unlocked
525and locked again before @code{scm_cond_wait} returns.
526@end deftypefn
527
528@deftypefn {C Function} void scm_cond_timedwait (scm_t_cond *c, scm_t_mutex *m, timespec *abstime)
529Wait for @var{c} to be signalled as with @code{scm_cond_wait} but
530don't wait longer than the point in time specified by @var{abstime}.
531when the waiting is aborted, zero is returned; non-zero else.
532@end deftypefn
533
534@deftypefn {C Function} void scm_cond_signal (scm_t_cond *c)
535Signal the condition variable @var{c}. When one or more threads are
536waiting for it to be signalled, select one arbitrarily and let its
537wait succeed.
538@end deftypefn
539
540@deftypefn {C Function} void scm_cond_broadcast (scm_t_cond *c)
541Signal the condition variable @var{c}. When there are threads waiting
542for it to be signalled, wake them all up and make all their waits
543succeed.
544@end deftypefn
545
546@deftp {C Type} scm_t_key
547This type represents a key for a thread-specific value.
548@end deftp
549
550@deftypefn {C Function} void scm_key_create (scm_t_key *keyp)
551Create a new key for a thread-specific value. Each thread has its own
552value associated to such a handle. The new handle is stored into
553@var{keyp}, which must be non-NULL.
554@end deftypefn
555
556@deftypefn {C Function} void scm_key_delete (scm_t_key key)
557This function makes @var{key} invalid as a key for thread-specific data.
558@end deftypefn
559
560@deftypefn {C Function} void scm_key_setspecific (scm_t_key key, const void *value)
561Associate @var{value} with @var{key} in the calling thread.
562@end deftypefn
563
564@deftypefn {C Function} int scm_key_getspecific (scm_t_key key)
565Return the value currently associated with @var{key} in the calling
566thread. When @code{scm_key_setspecific} has not yet been called in
567this thread with this key, @code{NULL} is returned.
568@end deftypefn
569
570@deftypefn {C Function} int scm_thread_select (...)
571This function does the same thing as the system's @code{select}
572function, but in a way that is friendly to the thread implementation.
573You should call it in preference to the system @code{select}.
574@end deftypefn
575
576@node Fluids
577@subsection Fluids
578
579@cindex fluids
580
581Fluids are objects to store values in. They have a few properties
582which make them useful in certain situations: Fluids can have one
583value per dynamic root (@pxref{Dynamic Roots}), so that changes to the
584value in a fluid are only visible in the same dynamic root. Since
585threads are executed in separate dynamic roots, fluids can be used for
586thread local storage (@pxref{Threads}).
587
588Fluids can be used to simulate the desirable effects of dynamically
589scoped variables. Dynamically scoped variables are useful when you
590want to set a variable to a value during some dynamic extent in the
591execution of your program and have them revert to their original value
592when the control flow is outside of this dynamic extent. See the
593description of @code{with-fluids} below for details.
594
595New fluids are created with @code{make-fluid} and @code{fluid?} is
596used for testing whether an object is actually a fluid. The values
597stored in a fluid can be accessed with @code{fluid-ref} and
598@code{fluid-set!}.
599
600@deffn {Scheme Procedure} make-fluid
601@deffnx {C Function} scm_make_fluid ()
602Return a newly created fluid.
603Fluids are objects of a certain type (a smob) that can hold one SCM
604value per dynamic root. That is, modifications to this value are
605only visible to code that executes within the same dynamic root as
606the modifying code. When a new dynamic root is constructed, it
607inherits the values from its parent. Because each thread executes
608in its own dynamic root, you can use fluids for thread local storage.
609@end deffn
610
611@deffn {Scheme Procedure} fluid? obj
612@deffnx {C Function} scm_fluid_p (obj)
613Return @code{#t} iff @var{obj} is a fluid; otherwise, return
614@code{#f}.
615@end deffn
616
617@deffn {Scheme Procedure} fluid-ref fluid
618@deffnx {C Function} scm_fluid_ref (fluid)
619Return the value associated with @var{fluid} in the current
620dynamic root. If @var{fluid} has not been set, then return
621@code{#f}.
622@end deffn
623
624@deffn {Scheme Procedure} fluid-set! fluid value
625@deffnx {C Function} scm_fluid_set_x (fluid, value)
626Set the value associated with @var{fluid} in the current dynamic root.
627@end deffn
628
629@code{with-fluids*} temporarily changes the values of one or more fluids,
630so that the given procedure and each procedure called by it access the
631given values. After the procedure returns, the old values are restored.
632
cdf1ad3b
MV
633@deffn {Scheme Procedure} with-fluid* fluid value thunk
634@deffnx {C Function} scm_with_fluid (fluid, value, thunk)
635Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
636@var{thunk} must be a procedure with no argument.
637@end deffn
638
07d83abe
MV
639@deffn {Scheme Procedure} with-fluids* fluids values thunk
640@deffnx {C Function} scm_with_fluids (fluids, values, thunk)
641Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
642@var{fluids} must be a list of fluids and @var{values} must be the
643same number of their values to be applied. Each substitution is done
644in the order given. @var{thunk} must be a procedure with no argument.
645it is called inside a @code{dynamic-wind} and the fluids are
646set/restored when control enter or leaves the established dynamic
647extent.
648@end deffn
649
650@deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
651Execute @var{body...} while each @var{fluid} is set to the
652corresponding @var{value}. Both @var{fluid} and @var{value} are
653evaluated and @var{fluid} must yield a fluid. @var{body...} is
654executed inside a @code{dynamic-wind} and the fluids are set/restored
655when control enter or leaves the established dynamic extent.
656@end deffn
657
658@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
659@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
660The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
661except that it takes a C function to call instead of a Scheme thunk.
662
663The function @code{scm_c_with_fluid} is similar but only allows one
664fluid to be set instead of a list.
665@end deftypefn
666
667@deftypefn {C Function} void scm_frame_fluid (SCM fluid, SCM val)
668This function must be used inside a pair of calls to
669@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
670During the dynamic extent of the frame, the fluid @var{fluid} is set
671to @var{val}.
672
673More precisely, the value of the fluid is swapped with a `backup'
674value whenever the frame is entered or left. The backup value is
675initialized with the @var{val} argument.
676@end deftypefn
677
678@node Futures
679@subsection Futures
680@cindex futures
681
682Futures are a convenient way to run a calculation in a new thread, and
683only wait for the result when it's actually needed.
684
685Futures are similar to promises (@pxref{Delayed Evaluation}), in that
686they allow mainline code to continue immediately. But @code{delay}
687doesn't evaluate at all until forced, whereas @code{future} starts
688immediately in a new thread.
689
690@deffn {syntax} future expr
691Begin evaluating @var{expr} in a new thread, and return a ``future''
692object representing the calculation.
693@end deffn
694
695@deffn {Scheme Procedure} make-future thunk
696@deffnx {C Function} scm_make_future (thunk)
697Begin evaluating the call @code{(@var{thunk})} in a new thread, and
698return a ``future'' object representing the calculation.
699@end deffn
700
701@deffn {Scheme Procedure} future-ref f
702@deffnx {C Function} scm_future_ref (f)
703Return the value computed by the future @var{f}. If @var{f} has not
704yet finished executing then wait for it to do so.
705@end deffn
706
707
708@node Parallel Forms
709@subsection Parallel forms
710@cindex parallel forms
711
712The functions described in this section are available from
713
714@example
715(use-modules (ice-9 threads))
716@end example
717
718@deffn syntax parallel expr1 @dots{} exprN
af1323c5 719Evaluate each @var{expr} expression in parallel, each in its own thread.
07d83abe
MV
720Return the results as a set of @var{N} multiple values
721(@pxref{Multiple Values}).
722@end deffn
723
724@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
af1323c5 725Evaluate each @var{expr} in parallel, each in its own thread, then bind
07d83abe
MV
726the results to the corresponding @var{var} variables and evaluate
727@var{body}.
728
729@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
730expressions for the bindings are evaluated in parallel.
731@end deffn
732
733@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
734@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
735Call @var{proc} on the elements of the given lists. @code{par-map}
736returns a list comprising the return values from @var{proc}.
737@code{par-for-each} returns an unspecified value, but waits for all
738calls to complete.
739
740The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
741@var{elemN})}, where each @var{elem} is from the corresponding
742@var{lst}. Each @var{lst} must be the same length. The calls are
af1323c5 743made in parallel, each in its own thread.
07d83abe
MV
744
745These functions are like @code{map} and @code{for-each} (@pxref{List
746Mapping}), but make their @var{proc} calls in parallel.
747@end deffn
748
749@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
750@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
751Call @var{proc} on the elements of the given lists, in the same way as
752@code{par-map} and @code{par-for-each} above, but use no more than
af1323c5 753@var{n} threads at any one time. The order in which calls are
07d83abe
MV
754initiated within that threads limit is unspecified.
755
756These functions are good for controlling resource consumption if
757@var{proc} calls might be costly, or if there are many to be made. On
758a dual-CPU system for instance @math{@var{n}=4} might be enough to
759keep the CPUs utilized, and not consume too much memory.
760@end deffn
761
762@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
763Apply @var{pproc} to the elements of the given lists, and apply
764@var{sproc} to each result returned by @var{pproc}. The final return
765value is unspecified, but all calls will have been completed before
766returning.
767
768The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
769@var{elemN}))}, where each @var{elem} is from the corresponding
770@var{lst}. Each @var{lst} must have the same number of elements.
771
af1323c5
KR
772The @var{pproc} calls are made in parallel, in separate threads. No more
773than @var{n} threads are used at any one time. The order in which
07d83abe
MV
774@var{pproc} calls are initiated within that limit is unspecified.
775
776The @var{sproc} calls are made serially, in list element order, one at
777a time. @var{pproc} calls on later elements may execute in parallel
778with the @var{sproc} calls. Exactly which thread makes each
779@var{sproc} call is unspecified.
780
781This function is designed for individual calculations that can be done
782in parallel, but with results needing to be handled serially, for
783instance to write them to a file. The @var{n} limit on threads
784controls system resource usage when there are many calculations or
785when they might be costly.
786
787It will be seen that @code{n-for-each-par-map} is like a combination
788of @code{n-par-map} and @code{for-each},
789
790@example
af1323c5 791(for-each sproc (n-par-map n pproc lst1 ... lstN))
07d83abe
MV
792@end example
793
794@noindent
795But the actual implementation is more efficient since each @var{sproc}
796call, in turn, can be initiated once the relevant @var{pproc} call has
797completed, it doesn't need to wait for all to finish.
798@end deffn
799
800
3cf066df
KR
801@node Mutexes
802@subsection Mutexes
803@cindex mutex
804
805A mutex is a thread synchronization object, it can be used by threads
806to control access to a shared resource. A mutex can be locked to
807indicate a resource is in use, and other threads can then block on the
808mutex to wait for the resource (or can just test and do something else
809if not available). ``Mutex'' is short for ``mutual exclusion''.
810
811There are two types of mutexes, ``standard'' and ``fair''. They're
812created by @code{make-mutex} and @code{make-fair-mutex} respectively,
813the operation functions are then common to both.
814
815Note that for both types of mutex there's no protection against a
816``deadly embrace''. For instance if one thread has locked mutex A and
817is waiting on mutex B, but another thread owns B and is waiting on A,
818then an endless wait will occur (in the current implementation).
819Acquiring requisite mutexes in a fixed order (like always A before B)
820in all threads is one way to avoid such problems.
821
822@sp 1
823@deffn {Scheme Procedure} make-mutex
824@deffnx {Scheme Procedure} make-fair-mutex
825Return a new mutex object.
826
827@code{make-mutex} creates a standard mutex. This is fast, but its
828features are restricted. Recursive locking (multiple lock calls by
829one thread) is not permitted, and an unlock can be done only when
830already locked and only by the owning thread. When multiple threads
831are blocked waiting to acquire the mutex, it's unspecified which will
832get it next.
833
834@code{make-fair-mutex} creates a fair mutex. This has more features
835and error checking. Recursive locking is allowed, a given thread can
836make multiple lock calls and the mutex is released when a balancing
837number of unlocks are done. Other threads blocked waiting to acquire
838the mutex form a queue and the one waiting longest will be the next to
839acquire it.
840@end deffn
841
842@deffn {Scheme Procedure} lock-mutex mutex
843Lock @var{mutex}. If the mutex is already locked by another thread
844then block and return only when @var{mutex} has been acquired.
845
846For standard mutexes (@code{make-mutex}), if the thread has itself
847already locked @var{mutex} it must not call @code{lock-mutex} on it a
848further time. Behaviour is unspecified if this is done.
849
850For a fair mutex (@code{make-fair-mutex}), if the thread has itself
851already locked @var{mutex}, then a further @code{lock-mutex} call
852increments the lock count. An additional @code{unlock-mutex} will be
853required to finally release.
854
855When a system async (@pxref{System asyncs}) is activated for a thread
856blocked in @code{lock-mutex}, the wait is interrupted and the async is
857executed. When the async returns the wait resumes.
858@end deffn
859
860@deffn {Scheme Procedure} try-mutex mutex
861Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
862be acquired immediately then this is done and the return is @code{#t}.
863If @var{mutex} is locked by some other thread then nothing is done and
864the return is @code{#f}.
865@end deffn
866
867@deffn {Scheme Procedure} unlock-mutex mutex
868Unlock @var{mutex}.
869
870For a standard mutex (@code{make-mutex}), if @var{mutex} is not locked
871by the calling thread then behaviour is unspecified.
872
873For a fair mutex (@code{make-fair-mutex}), if @var{mutex} is not
874locked by the calling thread then an error is thrown.
875@end deffn
876
877@sp 1
878The following are higher level operations on mutexes. These are
879available from
880
881@example
882(use-modules (ice-9 threads))
883@end example
884
885@deffn macro with-mutex mutex [body@dots{}]
886Lock @var{mutex}, evaluate the @var{body} forms, then unlock
887@var{mutex}. The return value is the return from the last @var{body}
888form.
889
890The lock, body and unlock form the branches of a @code{dynamic-wind}
891(@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
892error or new continuation exits @var{body}, and is re-locked if
893@var{body} is re-entered by a captured continuation.
894@end deffn
895
896@deffn macro monitor body@dots{}
897Evaluate the @var{body} forms, with a mutex locked so only one thread
898can execute that code at any one time. The return value is the return
899from the last @var{body} form.
900
901Each @code{monitor} form has its own private mutex and the locking and
902evaluation is as per @code{with-mutex} above. A standard mutex
903(@code{make-mutex}) is used, which means @var{body} must not
904recursively re-enter the @code{monitor} form.
905
906The term ``monitor'' comes from operating system theory, where it
907means a particular bit of code managing access to some resource and
908which only ever executes on behalf of one process at any one time.
909@end deffn
910
911@sp 1
912The following provide access to standard mutexes from C code.
913
914@deftp {C Data Type} scm_t_mutex
915A mutex, to be used with @code{scm_mutex_init}, etc.
916@end deftp
917
918@deftypefn {C Function} void scm_mutex_init (scm_t_mutex *m)
919Initialize the mutex structure pointed to by @var{m}.
920@end deftypefn
921
922@deftypefn {C Function} void scm_mutex_destroy (scm_t_mutex *m)
923Free all resources associated with @var{m}.
924@end deftypefn
925
926@deftypefn {C Function} void scm_mutex_lock (scm_t_mutex *m)
927Lock the mutex @var{m}. This is as per @code{lock-mutex} above on a
928standard mutex.
929@end deftypefn
930
931@deftypefn {C Function} int scm_mutex_trylock (scm_t_mutex *m)
932Attempt to lock mutex @var{m}, as per @code{scm_mutex_lock}. If
933@var{m} is unlocked then this is done and the return is non-zero. If
934@var{m} is already locked by another thread then do nothing and return
935zero.
936@end deftypefn
937
938@deftypefn {C Function} void scm_mutex_unlock (scm_t_mutex *m)
939Unlock the mutex @var{m}. The mutex must have been locked by the
940current thread, otherwise the behavior is undefined.
941@end deftypefn
942
943
07d83abe
MV
944@c Local Variables:
945@c TeX-master: "guile.texi"
946@c End: