api-scheduling.texi 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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, 2008
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @page
  7. @node Scheduling
  8. @section Threads, Mutexes, Asyncs and Dynamic Roots
  9. [FIXME: This is pasted in from Tom Lord's original guile.texi chapter
  10. plus the Cygnus programmer's manual; it should be *very* carefully
  11. reviewed and largely reorganized.]
  12. @menu
  13. * Arbiters:: Synchronization primitives.
  14. * Asyncs:: Asynchronous procedure invocation.
  15. * Continuation Barriers:: Protection from non-local control flow.
  16. * Threads:: Multiple threads of execution.
  17. * Mutexes and Condition Variables:: Synchronization primitives.
  18. * Blocking:: How to block properly in guile mode.
  19. * Critical Sections:: Avoiding concurrency and reentries.
  20. * Fluids and Dynamic States:: Thread-local variables, etc.
  21. * Parallel Forms:: Parallel execution of forms.
  22. @end menu
  23. @node Arbiters
  24. @subsection Arbiters
  25. @cindex arbiters
  26. Arbiters are synchronization objects, they can be used by threads to
  27. control access to a shared resource. An arbiter can be locked to
  28. indicate a resource is in use, and unlocked when done.
  29. An arbiter is like a light-weight mutex (@pxref{Mutexes and Condition
  30. Variables}). It uses less memory and may be faster, but there's no
  31. way for a thread to block waiting on an arbiter, it can only test and
  32. get the status returned.
  33. @deffn {Scheme Procedure} make-arbiter name
  34. @deffnx {C Function} scm_make_arbiter (name)
  35. Return an object of type arbiter and name @var{name}. Its
  36. state is initially unlocked. Arbiters are a way to achieve
  37. process synchronization.
  38. @end deffn
  39. @deffn {Scheme Procedure} try-arbiter arb
  40. @deffnx {C Function} scm_try_arbiter (arb)
  41. @deffnx {C Function} scm_try_arbiter (arb)
  42. If @var{arb} is unlocked, then lock it and return @code{#t}.
  43. If @var{arb} is already locked, then do nothing and return
  44. @code{#f}.
  45. @end deffn
  46. @deffn {Scheme Procedure} release-arbiter arb
  47. @deffnx {C Function} scm_release_arbiter (arb)
  48. If @var{arb} is locked, then unlock it and return @code{#t}. If
  49. @var{arb} is already unlocked, then do nothing and return @code{#f}.
  50. Typical usage is for the thread which locked an arbiter to later
  51. release it, but that's not required, any thread can release it.
  52. @end deffn
  53. @node Asyncs
  54. @subsection Asyncs
  55. @cindex asyncs
  56. @cindex user asyncs
  57. @cindex system asyncs
  58. Asyncs are a means of deferring the excution of Scheme code until it is
  59. safe to do so.
  60. Guile provides two kinds of asyncs that share the basic concept but are
  61. otherwise quite different: system asyncs and user asyncs. System asyncs
  62. are integrated into the core of Guile and are executed automatically
  63. when the system is in a state to allow the execution of Scheme code.
  64. For example, it is not possible to execute Scheme code in a POSIX signal
  65. handler, but such a signal handler can queue a system async to be
  66. executed in the near future, when it is safe to do so.
  67. System asyncs can also be queued for threads other than the current one.
  68. This way, you can cause threads to asynchronously execute arbitrary
  69. code.
  70. User asyncs offer a convenient means of queueing procedures for future
  71. execution and triggering this execution. They will not be executed
  72. automatically.
  73. @menu
  74. * System asyncs::
  75. * User asyncs::
  76. @end menu
  77. @node System asyncs
  78. @subsubsection System asyncs
  79. To cause the future asynchronous execution of a procedure in a given
  80. thread, use @code{system-async-mark}.
  81. Automatic invocation of system asyncs can be temporarily disabled by
  82. calling @code{call-with-blocked-asyncs}. This function works by
  83. temporarily increasing the @emph{async blocking level} of the current
  84. thread while a given procedure is running. The blocking level starts
  85. out at zero, and whenever a safe point is reached, a blocking level
  86. greater than zero will prevent the execution of queued asyncs.
  87. Analogously, the procedure @code{call-with-unblocked-asyncs} will
  88. temporarily decrease the blocking level of the current thread. You
  89. can use it when you want to disable asyncs by default and only allow
  90. them temporarily.
  91. In addition to the C versions of @code{call-with-blocked-asyncs} and
  92. @code{call-with-unblocked-asyncs}, C code can use
  93. @code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
  94. inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
  95. unblock system asyncs temporarily.
  96. @deffn {Scheme Procedure} system-async-mark proc [thread]
  97. @deffnx {C Function} scm_system_async_mark (proc)
  98. @deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
  99. Mark @var{proc} (a procedure with zero arguments) for future execution
  100. in @var{thread}. When @var{proc} has already been marked for
  101. @var{thread} but has not been executed yet, this call has no effect.
  102. When @var{thread} is omitted, the thread that called
  103. @code{system-async-mark} is used.
  104. This procedure is not safe to be called from signal handlers. Use
  105. @code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
  106. signal handlers.
  107. @end deffn
  108. @c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
  109. @c scm_c_call_with_unblocked_asyncs puts "void" into the function
  110. @c index. Would prefer to use @deftypefnx if makeinfo allowed that,
  111. @c or a @deftypefn with an empty return type argument if it didn't
  112. @c introduce an extra space.
  113. @deffn {Scheme Procedure} call-with-blocked-asyncs proc
  114. @deffnx {C Function} scm_call_with_blocked_asyncs (proc)
  115. @deffnx {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
  116. @findex scm_c_call_with_blocked_asyncs
  117. Call @var{proc} and block the execution of system asyncs by one level
  118. for the current thread while it is running. Return the value returned
  119. by @var{proc}. For the first two variants, call @var{proc} with no
  120. arguments; for the third, call it with @var{data}.
  121. @end deffn
  122. @deffn {Scheme Procedure} call-with-unblocked-asyncs proc
  123. @deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
  124. @deffnx {C Function} {void *} scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
  125. @findex scm_c_call_with_unblocked_asyncs
  126. Call @var{proc} and unblock the execution of system asyncs by one
  127. level for the current thread while it is running. Return the value
  128. returned by @var{proc}. For the first two variants, call @var{proc}
  129. with no arguments; for the third, call it with @var{data}.
  130. @end deffn
  131. @deftypefn {C Function} void scm_dynwind_block_asyncs ()
  132. This function must be used inside a pair of calls to
  133. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  134. Wind}). During the dynwind context, asyncs are blocked by one level.
  135. @end deftypefn
  136. @deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
  137. This function must be used inside a pair of calls to
  138. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  139. Wind}). During the dynwind context, asyncs are unblocked by one
  140. level.
  141. @end deftypefn
  142. @node User asyncs
  143. @subsubsection User asyncs
  144. A user async is a pair of a thunk (a parameterless procedure) and a
  145. mark. Setting the mark on a user async will cause the thunk to be
  146. executed when the user async is passed to @code{run-asyncs}. Setting
  147. the mark more than once is satisfied by one execution of the thunk.
  148. User asyncs are created with @code{async}. They are marked with
  149. @code{async-mark}.
  150. @deffn {Scheme Procedure} async thunk
  151. @deffnx {C Function} scm_async (thunk)
  152. Create a new user async for the procedure @var{thunk}.
  153. @end deffn
  154. @deffn {Scheme Procedure} async-mark a
  155. @deffnx {C Function} scm_async_mark (a)
  156. Mark the user async @var{a} for future execution.
  157. @end deffn
  158. @deffn {Scheme Procedure} run-asyncs list_of_a
  159. @deffnx {C Function} scm_run_asyncs (list_of_a)
  160. Execute all thunks from the marked asyncs of the list @var{list_of_a}.
  161. @end deffn
  162. @node Continuation Barriers
  163. @subsection Continuation Barriers
  164. The non-local flow of control caused by continuations might sometimes
  165. not be wanted. You can use @code{with-continuation-barrier} etc to
  166. errect fences that continuations can not pass.
  167. @deffn {Scheme Procedure} with-continuation-barrier proc
  168. @deffnx {C Function} scm_with_continuation_barrier (proc)
  169. Call @var{proc} and return its result. Do not allow the invocation of
  170. continuations that would leave or enter the dynamic extent of the call
  171. to @code{with-continuation-barrier}. Such an attempt causes an error
  172. to be signaled.
  173. Throws (such as errors) that are not caught from within @var{proc} are
  174. caught by @code{with-continuation-barrier}. In that case, a short
  175. message is printed to the current error port and @code{#f} is returned.
  176. Thus, @code{with-continuation-barrier} returns exactly once.
  177. @end deffn
  178. @deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
  179. Like @code{scm_with_continuation_barrier} but call @var{func} on
  180. @var{data}. When an error is caught, @code{NULL} is returned.
  181. @end deftypefn
  182. @node Threads
  183. @subsection Threads
  184. @cindex threads
  185. @cindex Guile threads
  186. @cindex POSIX threads
  187. @deffn {Scheme Procedure} all-threads
  188. @deffnx {C Function} scm_all_threads ()
  189. Return a list of all threads.
  190. @end deffn
  191. @deffn {Scheme Procedure} current-thread
  192. @deffnx {C Function} scm_current_thread ()
  193. Return the thread that called this function.
  194. @end deffn
  195. @c begin (texi-doc-string "guile" "call-with-new-thread")
  196. @deffn {Scheme Procedure} call-with-new-thread thunk [handler]
  197. Call @code{thunk} in a new thread and with a new dynamic state,
  198. returning the new thread. The procedure @var{thunk} is called via
  199. @code{with-continuation-barrier}.
  200. When @var{handler} is specified, then @var{thunk} is called from
  201. within a @code{catch} with tag @code{#t} that has @var{handler} as its
  202. handler. This catch is established inside the continuation barrier.
  203. Once @var{thunk} or @var{handler} returns, the return value is made
  204. the @emph{exit value} of the thread and the thread is terminated.
  205. @end deffn
  206. @deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
  207. Call @var{body} in a new thread, passing it @var{body_data}, returning
  208. the new thread. The function @var{body} is called via
  209. @code{scm_c_with_continuation_barrier}.
  210. When @var{handler} is non-@code{NULL}, @var{body} is called via
  211. @code{scm_internal_catch} with tag @code{SCM_BOOL_T} that has
  212. @var{handler} and @var{handler_data} as the handler and its data. This
  213. catch is established inside the continuation barrier.
  214. Once @var{body} or @var{handler} returns, the return value is made the
  215. @emph{exit value} of the thread and the thread is terminated.
  216. @end deftypefn
  217. @c begin (texi-doc-string "guile" "join-thread")
  218. @deffn {Scheme Procedure} join-thread thread
  219. @deffnx {C Function} scm_join_thread (thread)
  220. Wait for @var{thread} to terminate and return its exit value. Threads
  221. that have not been created with @code{call-with-new-thread} or
  222. @code{scm_spawn_thread} have an exit value of @code{#f}.
  223. @end deffn
  224. @deffn {Scheme Procedure} thread-exited? thread
  225. @deffnx {C Function} scm_thread_exited_p (thread)
  226. Return @code{#t} iff @var{thread} has exited.
  227. @end deffn
  228. @c begin (texi-doc-string "guile" "yield")
  229. @deffn {Scheme Procedure} yield
  230. If one or more threads are waiting to execute, calling yield forces an
  231. immediate context switch to one of them. Otherwise, yield has no effect.
  232. @end deffn
  233. Higher level thread procedures are available by loading the
  234. @code{(ice-9 threads)} module. These provide standardized
  235. thread creation.
  236. @deffn macro make-thread proc [args@dots{}]
  237. Apply @var{proc} to @var{args} in a new thread formed by
  238. @code{call-with-new-thread} using a default error handler that display
  239. the error to the current error port. The @var{args@dots{}}
  240. expressions are evaluated in the new thread.
  241. @end deffn
  242. @deffn macro begin-thread first [rest@dots{}]
  243. Evaluate forms @var{first} and @var{rest} in a new thread formed by
  244. @code{call-with-new-thread} using a default error handler that display
  245. the error to the current error port.
  246. @end deffn
  247. @node Mutexes and Condition Variables
  248. @subsection Mutexes and Condition Variables
  249. @cindex mutex
  250. @cindex condition variable
  251. A mutex is a thread synchronization object, it can be used by threads
  252. to control access to a shared resource. A mutex can be locked to
  253. indicate a resource is in use, and other threads can then block on the
  254. mutex to wait for the resource (or can just test and do something else
  255. if not available). ``Mutex'' is short for ``mutual exclusion''.
  256. There are two types of mutexes in Guile, ``standard'' and
  257. ``recursive''. They're created by @code{make-mutex} and
  258. @code{make-recursive-mutex} respectively, the operation functions are
  259. then common to both.
  260. Note that for both types of mutex there's no protection against a
  261. ``deadly embrace''. For instance if one thread has locked mutex A and
  262. is waiting on mutex B, but another thread owns B and is waiting on A,
  263. then an endless wait will occur (in the current implementation).
  264. Acquiring requisite mutexes in a fixed order (like always A before B)
  265. in all threads is one way to avoid such problems.
  266. @sp 1
  267. @deffn {Scheme Procedure} make-mutex
  268. @deffnx {C Function} scm_make_mutex ()
  269. Return a new standard mutex. It is initially unlocked.
  270. @end deffn
  271. @deffn {Scheme Procedure} make-recursive-mutex
  272. @deffnx {C Function} scm_make_recursive_mutex ()
  273. Create a new recursive mutex. It is initialloy unlocked.
  274. @end deffn
  275. @deffn {Scheme Procedure} lock-mutex mutex
  276. @deffnx {C Function} scm_lock_mutex (mutex)
  277. Lock @var{mutex}. If the mutex is already locked by another thread
  278. then block and return only when @var{mutex} has been acquired.
  279. For standard mutexes (@code{make-mutex}), and error is signalled if
  280. the thread has itself already locked @var{mutex}.
  281. For a recursive mutex (@code{make-recursive-mutex}), if the thread has
  282. itself already locked @var{mutex}, then a further @code{lock-mutex}
  283. call increments the lock count. An additional @code{unlock-mutex}
  284. will be required to finally release.
  285. When a system async (@pxref{System asyncs}) is activated for a thread
  286. blocked in @code{lock-mutex}, the wait is interrupted and the async is
  287. executed. When the async returns, the wait resumes.
  288. @end deffn
  289. @deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
  290. Arrange for @var{mutex} to be locked whenever the current dynwind
  291. context is entered and to be unlocked when it is exited.
  292. @end deftypefn
  293. @deffn {Scheme Procedure} try-mutex mx
  294. @deffnx {C Function} scm_try_mutex (mx)
  295. Try to lock @var{mutex} as per @code{lock-mutex}. If @var{mutex} can
  296. be acquired immediately then this is done and the return is @code{#t}.
  297. If @var{mutex} is locked by some other thread then nothing is done and
  298. the return is @code{#f}.
  299. @end deffn
  300. @deffn {Scheme Procedure} unlock-mutex mutex
  301. @deffnx {C Function} scm_unlock_mutex (mutex)
  302. Unlock @var{mutex}. An error is signalled if @var{mutex} is not
  303. locked by the calling thread.
  304. @end deffn
  305. @deffn {Scheme Procedure} make-condition-variable
  306. @deffnx {C Function} scm_make_condition_variable ()
  307. Return a new condition variable.
  308. @end deffn
  309. @deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
  310. @deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
  311. Wait until @var{condvar} has been signalled. While waiting,
  312. @var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
  313. is locked again when this function returns. When @var{time} is given,
  314. it specifies a point in time where the waiting should be aborted. It
  315. can be either a integer as returned by @code{current-time} or a pair
  316. as returned by @code{gettimeofday}. When the waiting is aborted,
  317. @code{#f} is returned. When the condition variable has in fact been
  318. signalled, @code{#t} is returned. The mutex is re-locked in any case
  319. before @code{wait-condition-variable} returns.
  320. When a system async is activated for a thread that is blocked in a
  321. call to @code{wait-condition-variable}, the waiting is interrupted,
  322. the mutex is locked, and the async is executed. When the async
  323. returns, the mutex is unlocked again and the waiting is resumed. When
  324. the thread block while re-acquiring the mutex, execution of asyncs is
  325. blocked.
  326. @end deffn
  327. @deffn {Scheme Procedure} signal-condition-variable condvar
  328. @deffnx {C Function} scm_signal_condition_variable (condvar)
  329. Wake up one thread that is waiting for @var{condvar}.
  330. @end deffn
  331. @deffn {Scheme Procedure} broadcast-condition-variable condvar
  332. @deffnx {C Function} scm_broadcast_condition_variable (condvar)
  333. Wake up all threads that are waiting for @var{condvar}.
  334. @end deffn
  335. @sp 1
  336. The following are higher level operations on mutexes. These are
  337. available from
  338. @example
  339. (use-modules (ice-9 threads))
  340. @end example
  341. @deffn macro with-mutex mutex [body@dots{}]
  342. Lock @var{mutex}, evaluate the @var{body} forms, then unlock
  343. @var{mutex}. The return value is the return from the last @var{body}
  344. form.
  345. The lock, body and unlock form the branches of a @code{dynamic-wind}
  346. (@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
  347. error or new continuation exits @var{body}, and is re-locked if
  348. @var{body} is re-entered by a captured continuation.
  349. @end deffn
  350. @deffn macro monitor body@dots{}
  351. Evaluate the @var{body} forms, with a mutex locked so only one thread
  352. can execute that code at any one time. The return value is the return
  353. from the last @var{body} form.
  354. Each @code{monitor} form has its own private mutex and the locking and
  355. evaluation is as per @code{with-mutex} above. A standard mutex
  356. (@code{make-mutex}) is used, which means @var{body} must not
  357. recursively re-enter the @code{monitor} form.
  358. The term ``monitor'' comes from operating system theory, where it
  359. means a particular bit of code managing access to some resource and
  360. which only ever executes on behalf of one process at any one time.
  361. @end deffn
  362. @node Blocking
  363. @subsection Blocking in Guile Mode
  364. A thread must not block outside of a libguile function while it is in
  365. guile mode. The following functions can be used to temporily leave
  366. guile mode or to perform some common blocking operations in a supported
  367. way.
  368. @deftypefn {C Function} {void *} scm_without_guile (void *(*func) (void *), void *data)
  369. Leave guile mode, call @var{func} on @var{data}, enter guile mode and
  370. return the result of calling @var{func}.
  371. While a thread has left guile mode, it must not call any libguile
  372. functions except @code{scm_with_guile} or @code{scm_without_guile} and
  373. must not use any libguile macros. Also, local variables of type
  374. @code{SCM} that are allocated while not in guile mode are not
  375. protected from the garbage collector.
  376. When used from non-guile mode, calling @code{scm_without_guile} is
  377. still allowed: it simply calls @var{func}. In that way, you can leave
  378. guile mode without having to know whether the current thread is in
  379. guile mode or not.
  380. @end deftypefn
  381. @deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
  382. Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
  383. the mutex.
  384. @end deftypefn
  385. @deftypefn {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
  386. @deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
  387. Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
  388. leaves guile mode while waiting for the condition variable.
  389. @end deftypefn
  390. @deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
  391. Like @code{select} but leaves guile mode while waiting. Also, the
  392. delivery of a system async causes this function to be interrupted with
  393. error code @code{EINTR}.
  394. @end deftypefn
  395. @deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
  396. Like @code{sleep}, but leaves guile mode while sleeping. Also, the
  397. delivery of a system async causes this function to be interrupted.
  398. @end deftypefn
  399. @deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
  400. Like @code{usleep}, but leaves guile mode while sleeping. Also, the
  401. delivery of a system async causes this function to be interrupted.
  402. @end deftypefn
  403. @node Critical Sections
  404. @subsection Critical Sections
  405. @deffn {C Macro} SCM_CRITICAL_SECTION_START
  406. @deffnx {C Macro} SCM_CRITICAL_SECTION_END
  407. These two macros can be used to delimit a critical section.
  408. Syntactically, they are both statements and need to be followed
  409. immediately by a semicolon.
  410. Executing @code{SCM_CRITICAL_SECTION_START} will lock a recursive
  411. mutex and block the executing of system asyncs. Executing
  412. @code{SCM_CRITICAL_SECTION_END} will unblock the execution of system
  413. asyncs and unlock the mutex. Thus, the code that executes between
  414. these two macros can only be executed in one thread at any one time
  415. and no system asyncs will run. However, because the mutex is a
  416. recursive one, the code might still be reentered by the same thread.
  417. You must either allow for this or avoid it, both by careful coding.
  418. On the other hand, critical sections delimited with these macros can
  419. be nested since the mutex is recursive.
  420. You must make sure that for each @code{SCM_CRITICAL_SECTION_START},
  421. the corresponding @code{SCM_CRITICAL_SECTION_END} is always executed.
  422. This means that no non-local exit (such as a signalled error) might
  423. happen, for example.
  424. @end deffn
  425. @deftypefn {C Function} void scm_dynwind_critical_section (SCM mutex)
  426. Call @code{scm_dynwind_lock_mutex} on @var{mutex} and call
  427. @code{scm_dynwind_block_asyncs}. When @var{mutex} is false, a recursive
  428. mutex provided by Guile is used instead.
  429. The effect of a call to @code{scm_dynwind_critical_section} is that
  430. the current dynwind context (@pxref{Dynamic Wind}) turns into a
  431. critical section. Because of the locked mutex, no second thread can
  432. enter it concurrently and because of the blocked asyncs, no system
  433. async can reenter it from the current thread.
  434. When the current thread reenters the critical section anyway, the kind
  435. of @var{mutex} determines what happens: When @var{mutex} is recursive,
  436. the reentry is allowed. When it is a normal mutex, an error is
  437. signalled.
  438. @end deftypefn
  439. @node Fluids and Dynamic States
  440. @subsection Fluids and Dynamic States
  441. @cindex fluids
  442. A @emph{fluid} is an object that can store one value per @emph{dynamic
  443. state}. Each thread has a current dynamic state, and when accessing a
  444. fluid, this current dynamic state is used to provide the actual value.
  445. In this way, fluids can be used for thread local storage, but they are
  446. in fact more flexible: dynamic states are objects of their own and can
  447. be made current for more than one thread at the same time, or only be
  448. made current temporarily, for example.
  449. Fluids can also be used to simulate the desirable effects of
  450. dynamically scoped variables. Dynamically scoped variables are useful
  451. when you want to set a variable to a value during some dynamic extent
  452. in the execution of your program and have them revert to their
  453. original value when the control flow is outside of this dynamic
  454. extent. See the description of @code{with-fluids} below for details.
  455. New fluids are created with @code{make-fluid} and @code{fluid?} is
  456. used for testing whether an object is actually a fluid. The values
  457. stored in a fluid can be accessed with @code{fluid-ref} and
  458. @code{fluid-set!}.
  459. @deffn {Scheme Procedure} make-fluid
  460. @deffnx {C Function} scm_make_fluid ()
  461. Return a newly created fluid.
  462. Fluids are objects that can hold one
  463. value per dynamic state. That is, modifications to this value are
  464. only visible to code that executes with the same dynamic state as
  465. the modifying code. When a new dynamic state is constructed, it
  466. inherits the values from its parent. Because each thread normally executes
  467. with its own dynamic state, you can use fluids for thread local storage.
  468. @end deffn
  469. @deffn {Scheme Procedure} fluid? obj
  470. @deffnx {C Function} scm_fluid_p (obj)
  471. Return @code{#t} iff @var{obj} is a fluid; otherwise, return
  472. @code{#f}.
  473. @end deffn
  474. @deffn {Scheme Procedure} fluid-ref fluid
  475. @deffnx {C Function} scm_fluid_ref (fluid)
  476. Return the value associated with @var{fluid} in the current
  477. dynamic root. If @var{fluid} has not been set, then return
  478. @code{#f}.
  479. @end deffn
  480. @deffn {Scheme Procedure} fluid-set! fluid value
  481. @deffnx {C Function} scm_fluid_set_x (fluid, value)
  482. Set the value associated with @var{fluid} in the current dynamic root.
  483. @end deffn
  484. @code{with-fluids*} temporarily changes the values of one or more fluids,
  485. so that the given procedure and each procedure called by it access the
  486. given values. After the procedure returns, the old values are restored.
  487. @deffn {Scheme Procedure} with-fluid* fluid value thunk
  488. @deffnx {C Function} scm_with_fluid (fluid, value, thunk)
  489. Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
  490. @var{thunk} must be a procedure with no argument.
  491. @end deffn
  492. @deffn {Scheme Procedure} with-fluids* fluids values thunk
  493. @deffnx {C Function} scm_with_fluids (fluids, values, thunk)
  494. Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
  495. @var{fluids} must be a list of fluids and @var{values} must be the
  496. same number of their values to be applied. Each substitution is done
  497. in the order given. @var{thunk} must be a procedure with no argument.
  498. it is called inside a @code{dynamic-wind} and the fluids are
  499. set/restored when control enter or leaves the established dynamic
  500. extent.
  501. @end deffn
  502. @deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
  503. Execute @var{body...} while each @var{fluid} is set to the
  504. corresponding @var{value}. Both @var{fluid} and @var{value} are
  505. evaluated and @var{fluid} must yield a fluid. @var{body...} is
  506. executed inside a @code{dynamic-wind} and the fluids are set/restored
  507. when control enter or leaves the established dynamic extent.
  508. @end deffn
  509. @deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
  510. @deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
  511. The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
  512. except that it takes a C function to call instead of a Scheme thunk.
  513. The function @code{scm_c_with_fluid} is similar but only allows one
  514. fluid to be set instead of a list.
  515. @end deftypefn
  516. @deftypefn {C Function} void scm_dynwind_fluid (SCM fluid, SCM val)
  517. This function must be used inside a pair of calls to
  518. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  519. Wind}). During the dynwind context, the fluid @var{fluid} is set to
  520. @var{val}.
  521. More precisely, the value of the fluid is swapped with a `backup'
  522. value whenever the dynwind context is entered or left. The backup
  523. value is initialized with the @var{val} argument.
  524. @end deftypefn
  525. @deffn {Scheme Procedure} make-dynamic-state [parent]
  526. @deffnx {C Function} scm_make_dynamic_state (parent)
  527. Return a copy of the dynamic state object @var{parent}
  528. or of the current dynamic state when @var{parent} is omitted.
  529. @end deffn
  530. @deffn {Scheme Procedure} dynamic-state? obj
  531. @deffnx {C Function} scm_dynamic_state_p (obj)
  532. Return @code{#t} if @var{obj} is a dynamic state object;
  533. return @code{#f} otherwise.
  534. @end deffn
  535. @deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
  536. Return non-zero if @var{obj} is a dynamic state object;
  537. return zero otherwise.
  538. @end deftypefn
  539. @deffn {Scheme Procedure} current-dynamic-state
  540. @deffnx {C Function} scm_current_dynamic_state ()
  541. Return the current dynamic state object.
  542. @end deffn
  543. @deffn {Scheme Procedure} set-current-dynamic-state state
  544. @deffnx {C Function} scm_set_current_dynamic_state (state)
  545. Set the current dynamic state object to @var{state}
  546. and return the previous current dynamic state object.
  547. @end deffn
  548. @deffn {Scheme Procedure} with-dynamic-state state proc
  549. @deffnx {C Function} scm_with_dynamic_state (state, proc)
  550. Call @var{proc} while @var{state} is the current dynamic
  551. state object.
  552. @end deffn
  553. @deftypefn {C Procedure} void scm_dynwind_current_dynamic_state (SCM state)
  554. Set the current dynamic state to @var{state} for the current dynwind
  555. context.
  556. @end deftypefn
  557. @deftypefn {C Procedure} {void *} scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
  558. Like @code{scm_with_dynamic_state}, but call @var{func} with
  559. @var{data}.
  560. @end deftypefn
  561. @c @node Futures
  562. @c @subsection Futures
  563. @c @cindex futures
  564. @c -- Futures are disabled for the time being, see futures.h for an
  565. @c -- explanation.
  566. @c Futures are a convenient way to run a calculation in a new thread, and
  567. @c only wait for the result when it's actually needed.
  568. @c Futures are similar to promises (@pxref{Delayed Evaluation}), in that
  569. @c they allow mainline code to continue immediately. But @code{delay}
  570. @c doesn't evaluate at all until forced, whereas @code{future} starts
  571. @c immediately in a new thread.
  572. @c @deffn {syntax} future expr
  573. @c Begin evaluating @var{expr} in a new thread, and return a ``future''
  574. @c object representing the calculation.
  575. @c @end deffn
  576. @c @deffn {Scheme Procedure} make-future thunk
  577. @c @deffnx {C Function} scm_make_future (thunk)
  578. @c Begin evaluating the call @code{(@var{thunk})} in a new thread, and
  579. @c return a ``future'' object representing the calculation.
  580. @c @end deffn
  581. @c @deffn {Scheme Procedure} future-ref f
  582. @c @deffnx {C Function} scm_future_ref (f)
  583. @c Return the value computed by the future @var{f}. If @var{f} has not
  584. @c yet finished executing then wait for it to do so.
  585. @c @end deffn
  586. @node Parallel Forms
  587. @subsection Parallel forms
  588. @cindex parallel forms
  589. The functions described in this section are available from
  590. @example
  591. (use-modules (ice-9 threads))
  592. @end example
  593. @deffn syntax parallel expr1 @dots{} exprN
  594. Evaluate each @var{expr} expression in parallel, each in its own thread.
  595. Return the results as a set of @var{N} multiple values
  596. (@pxref{Multiple Values}).
  597. @end deffn
  598. @deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
  599. Evaluate each @var{expr} in parallel, each in its own thread, then bind
  600. the results to the corresponding @var{var} variables and evaluate
  601. @var{body}.
  602. @code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
  603. expressions for the bindings are evaluated in parallel.
  604. @end deffn
  605. @deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
  606. @deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
  607. Call @var{proc} on the elements of the given lists. @code{par-map}
  608. returns a list comprising the return values from @var{proc}.
  609. @code{par-for-each} returns an unspecified value, but waits for all
  610. calls to complete.
  611. The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
  612. @var{elemN})}, where each @var{elem} is from the corresponding
  613. @var{lst}. Each @var{lst} must be the same length. The calls are
  614. made in parallel, each in its own thread.
  615. These functions are like @code{map} and @code{for-each} (@pxref{List
  616. Mapping}), but make their @var{proc} calls in parallel.
  617. @end deffn
  618. @deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
  619. @deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
  620. Call @var{proc} on the elements of the given lists, in the same way as
  621. @code{par-map} and @code{par-for-each} above, but use no more than
  622. @var{n} threads at any one time. The order in which calls are
  623. initiated within that threads limit is unspecified.
  624. These functions are good for controlling resource consumption if
  625. @var{proc} calls might be costly, or if there are many to be made. On
  626. a dual-CPU system for instance @math{@var{n}=4} might be enough to
  627. keep the CPUs utilized, and not consume too much memory.
  628. @end deffn
  629. @deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
  630. Apply @var{pproc} to the elements of the given lists, and apply
  631. @var{sproc} to each result returned by @var{pproc}. The final return
  632. value is unspecified, but all calls will have been completed before
  633. returning.
  634. The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
  635. @var{elemN}))}, where each @var{elem} is from the corresponding
  636. @var{lst}. Each @var{lst} must have the same number of elements.
  637. The @var{pproc} calls are made in parallel, in separate threads. No more
  638. than @var{n} threads are used at any one time. The order in which
  639. @var{pproc} calls are initiated within that limit is unspecified.
  640. The @var{sproc} calls are made serially, in list element order, one at
  641. a time. @var{pproc} calls on later elements may execute in parallel
  642. with the @var{sproc} calls. Exactly which thread makes each
  643. @var{sproc} call is unspecified.
  644. This function is designed for individual calculations that can be done
  645. in parallel, but with results needing to be handled serially, for
  646. instance to write them to a file. The @var{n} limit on threads
  647. controls system resource usage when there are many calculations or
  648. when they might be costly.
  649. It will be seen that @code{n-for-each-par-map} is like a combination
  650. of @code{n-par-map} and @code{for-each},
  651. @example
  652. (for-each sproc (n-par-map n pproc lst1 ... lstN))
  653. @end example
  654. @noindent
  655. But the actual implementation is more efficient since each @var{sproc}
  656. call, in turn, can be initiated once the relevant @var{pproc} call has
  657. completed, it doesn't need to wait for all to finish.
  658. @end deffn
  659. @c Local Variables:
  660. @c TeX-master: "guile.texi"
  661. @c End: