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