api-scheduling.texi 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. @c -*-texinfo-*-
  2. @c This is part of the GNU Guile Reference Manual.
  3. @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2007, 2009, 2010, 2012, 2013
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node Scheduling
  7. @section Threads, Mutexes, Asyncs and Dynamic Roots
  8. @menu
  9. * Threads:: Multiple threads of execution.
  10. * Thread Local Variables:: Some fluids are thread-local.
  11. * Asyncs:: Asynchronous interrupts.
  12. * Atomics:: Atomic references.
  13. * Mutexes and Condition Variables:: Synchronization primitives.
  14. * Blocking:: How to block properly in guile mode.
  15. * Futures:: Fine-grain parallelism.
  16. * Parallel Forms:: Parallel execution of forms.
  17. @end menu
  18. @node Threads
  19. @subsection Threads
  20. @cindex threads
  21. @cindex Guile threads
  22. @cindex POSIX threads
  23. Guile supports POSIX threads, unless it was configured with
  24. @code{--without-threads} or the host lacks POSIX thread support. When
  25. thread support is available, the @code{threads} feature is provided
  26. (@pxref{Feature Manipulation, @code{provided?}}).
  27. The procedures below manipulate Guile threads, which are wrappers around
  28. the system's POSIX threads. For application-level parallelism, using
  29. higher-level constructs, such as futures, is recommended
  30. (@pxref{Futures}).
  31. To use these facilities, load the @code{(ice-9 threads)} module.
  32. @example
  33. (use-modules (ice-9 threads))
  34. @end example
  35. @deffn {Scheme Procedure} all-threads
  36. @deffnx {C Function} scm_all_threads ()
  37. Return a list of all threads.
  38. @end deffn
  39. @deffn {Scheme Procedure} current-thread
  40. @deffnx {C Function} scm_current_thread ()
  41. Return the thread that called this function.
  42. @end deffn
  43. @deffn {Scheme Procedure} call-with-new-thread thunk [handler]
  44. Call @code{thunk} in a new thread and with a new dynamic state,
  45. returning the new thread. The procedure @var{thunk} is called via
  46. @code{with-continuation-barrier}.
  47. When @var{handler} is specified, then @var{thunk} is called from
  48. within a @code{catch} with tag @code{#t} that has @var{handler} as its
  49. handler. This catch is established inside the continuation barrier.
  50. Once @var{thunk} or @var{handler} returns, the return value is made
  51. the @emph{exit value} of the thread and the thread is terminated.
  52. @end deffn
  53. @deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
  54. Call @var{body} in a new thread, passing it @var{body_data}, returning
  55. the new thread. The function @var{body} is called via
  56. @code{scm_c_with_continuation_barrier}.
  57. When @var{handler} is non-@code{NULL}, @var{body} is called via
  58. @code{scm_internal_catch} with tag @code{SCM_BOOL_T} that has
  59. @var{handler} and @var{handler_data} as the handler and its data. This
  60. catch is established inside the continuation barrier.
  61. Once @var{body} or @var{handler} returns, the return value is made the
  62. @emph{exit value} of the thread and the thread is terminated.
  63. @end deftypefn
  64. @deffn {Scheme Procedure} thread? obj
  65. @deffnx {C Function} scm_thread_p (obj)
  66. Return @code{#t} ff @var{obj} is a thread; otherwise, return
  67. @code{#f}.
  68. @end deffn
  69. @deffn {Scheme Procedure} join-thread thread [timeout [timeoutval]]
  70. @deffnx {C Function} scm_join_thread (thread)
  71. @deffnx {C Function} scm_join_thread_timed (thread, timeout, timeoutval)
  72. Wait for @var{thread} to terminate and return its exit value. Only
  73. threads that were created with @code{call-with-new-thread} or
  74. @code{scm_spawn_thread} can be joinable; attempting to join a foreign
  75. thread will raise an error.
  76. When @var{timeout} is given, it specifies a point in time where the
  77. waiting should be aborted. It can be either an integer as returned by
  78. @code{current-time} or a pair as returned by @code{gettimeofday}. When
  79. the waiting is aborted, @var{timeoutval} is returned (if it is
  80. specified; @code{#f} is returned otherwise).
  81. @end deffn
  82. @deffn {Scheme Procedure} thread-exited? thread
  83. @deffnx {C Function} scm_thread_exited_p (thread)
  84. Return @code{#t} if @var{thread} has exited, or @code{#f} otherwise.
  85. @end deffn
  86. @deffn {Scheme Procedure} yield
  87. @deffnx {C Function} scm_yield (thread)
  88. If one or more threads are waiting to execute, calling yield forces an
  89. immediate context switch to one of them. Otherwise, yield has no effect.
  90. @end deffn
  91. @deffn {Scheme Procedure} cancel-thread thread . values
  92. @deffnx {C Function} scm_cancel_thread (thread)
  93. Asynchronously interrupt @var{thread} and ask it to terminate.
  94. @code{dynamic-wind} post thunks will run, but throw handlers will not.
  95. If @var{thread} has already terminated or been signaled to terminate,
  96. this function is a no-op. Calling @code{join-thread} on the thread will
  97. return the given @var{values}, if the cancel succeeded.
  98. Under the hood, thread cancellation uses @code{system-async-mark} and
  99. @code{abort-to-prompt}. @xref{Asyncs} for more on asynchronous
  100. interrupts.
  101. @end deffn
  102. @deffn macro make-thread proc arg @dots{}
  103. Apply @var{proc} to @var{arg} @dots{} in a new thread formed by
  104. @code{call-with-new-thread} using a default error handler that displays
  105. the error to the current error port. The @var{arg} @dots{}
  106. expressions are evaluated in the new thread.
  107. @end deffn
  108. @deffn macro begin-thread expr1 expr2 @dots{}
  109. Evaluate forms @var{expr1} @var{expr2} @dots{} in a new thread formed by
  110. @code{call-with-new-thread} using a default error handler that displays
  111. the error to the current error port.
  112. @end deffn
  113. One often wants to limit the number of threads running to be
  114. proportional to the number of available processors. These interfaces
  115. are therefore exported by (ice-9 threads) as well.
  116. @deffn {Scheme Procedure} total-processor-count
  117. @deffnx {C Function} scm_total_processor_count ()
  118. Return the total number of processors of the machine, which
  119. is guaranteed to be at least 1. A ``processor'' here is a
  120. thread execution unit, which can be either:
  121. @itemize
  122. @item an execution core in a (possibly multi-core) chip, in a
  123. (possibly multi- chip) module, in a single computer, or
  124. @item a thread execution unit inside a core in the case of
  125. @dfn{hyper-threaded} CPUs.
  126. @end itemize
  127. Which of the two definitions is used, is unspecified.
  128. @end deffn
  129. @deffn {Scheme Procedure} current-processor-count
  130. @deffnx {C Function} scm_current_processor_count ()
  131. Like @code{total-processor-count}, but return the number of
  132. processors available to the current process. See
  133. @code{setaffinity} and @code{getaffinity} for more
  134. information.
  135. @end deffn
  136. @node Thread Local Variables
  137. @subsection Thread-Local Variables
  138. Sometimes you want to establish a variable binding that is only valid
  139. for a given thread: a ``thread-local variable''.
  140. You would think that fluids or parameters would be Guile's answer for
  141. thread-local variables, since establishing a new fluid binding doesn't
  142. affect bindings in other threads. @xref{Fluids and Dynamic States}, or
  143. @xref{Parameters}. However, new threads inherit the fluid bindings that
  144. were in place in their creator threads. In this way, a binding
  145. established using a fluid (or a parameter) in a thread can escape to
  146. other threads, which might not be what you want. Or, it might escape
  147. via explicit reification via @code{current-dynamic-state}.
  148. Of course, this dynamic scoping might be exactly what you want; that's
  149. why fluids and parameters work this way, and is what you want for for
  150. many common parameters such as the current input and output ports, the
  151. current locale conversion parameters, and the like. Perhaps this is the
  152. case for most parameters, even. If your use case for thread-local
  153. bindings comes from a desire to isolate a binding from its setting in
  154. unrelated threads, then fluids and parameters apply nicely.
  155. On the other hand, if your use case is to prevent concurrent access to a
  156. value from multiple threads, then using vanilla fluids or parameters is
  157. not appropriate. For this purpose, Guile has @dfn{thread-local fluids}.
  158. A fluid created with @code{make-thread-local-fluid} won't be captured by
  159. @code{current-dynamic-state} and won't be propagated to new threads.
  160. @deffn {Scheme Procedure} make-thread-local-fluid [dflt]
  161. @deffnx {C Function} scm_make_thread_local_fluid (dflt)
  162. Return a newly created fluid, whose initial value is @var{dflt}, or
  163. @code{#f} if @var{dflt} is not given. Unlike fluids made with
  164. @code{make-fluid}, thread local fluids are not captured by
  165. @code{make-dynamic-state}. Similarly, a newly spawned child thread does
  166. not inherit thread-local fluid values from the parent thread.
  167. @end deffn
  168. @deffn {Scheme Procedure} fluid-thread-local? fluid
  169. @deffnx {C Function} scm_fluid_thread_local_p (fluid)
  170. Return @code{#t} if the fluid @var{fluid} is is thread-local, or
  171. @code{#f} otherwise.
  172. @end deffn
  173. For example:
  174. @example
  175. (define %thread-local (make-thread-local-fluid))
  176. (with-fluids ((%thread-local (compute-data)))
  177. ... (fluid-ref %thread-local) ...)
  178. @end example
  179. You can also make a thread-local parameter out of a thread-local fluid
  180. using the normal @code{fluid->parameter}:
  181. @example
  182. (define param (fluid->parameter (make-thread-local-fluid)))
  183. (parameterize ((param (compute-data)))
  184. ... (param) ...)
  185. @end example
  186. @node Asyncs
  187. @subsection Asynchronous Interrupts
  188. @cindex asyncs
  189. @cindex asynchronous interrupts
  190. @cindex interrupts
  191. Every Guile thread can be interrupted. Threads running Guile code will
  192. periodically check if there are pending interrupts and run them if
  193. necessary. To interrupt a thread, call @code{system-async-mark} on that
  194. thread.
  195. @deffn {Scheme Procedure} system-async-mark proc [thread]
  196. @deffnx {C Function} scm_system_async_mark (proc)
  197. @deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
  198. Enqueue @var{proc} (a procedure with zero arguments) for future
  199. execution in @var{thread}. When @var{proc} has already been enqueued
  200. for @var{thread} but has not been executed yet, this call has no effect.
  201. When @var{thread} is omitted, the thread that called
  202. @code{system-async-mark} is used.
  203. @end deffn
  204. Note that @code{scm_system_async_mark_for_thread} is not
  205. ``async-signal-safe'' and so cannot be called from a C signal handler.
  206. (Indeed in general, @code{libguile} functions are not safe to call from
  207. C signal handlers.)
  208. Though an interrupt procedure can have any side effect permitted to
  209. Guile code, asynchronous interrupts are generally used either for
  210. profiling or for prematurely cancelling a computation. The former case
  211. is mostly transparent to the program being run, by design, but the
  212. latter case can introduce bugs. Like finalizers (@pxref{Foreign Object
  213. Memory Management}), asynchronous interrupts introduce concurrency in a
  214. program. An asyncronous interrupt can run in the middle of some
  215. mutex-protected operation, for example, and potentially corrupt the
  216. program's state.
  217. If some bit of Guile code needs to temporarily inhibit interrupts, it
  218. can use @code{call-with-blocked-asyncs}. This function works by
  219. temporarily increasing the @emph{async blocking level} of the current
  220. thread while a given procedure is running. The blocking level starts
  221. out at zero, and whenever a safe point is reached, a blocking level
  222. greater than zero will prevent the execution of queued asyncs.
  223. Analogously, the procedure @code{call-with-unblocked-asyncs} will
  224. temporarily decrease the blocking level of the current thread. You
  225. can use it when you want to disable asyncs by default and only allow
  226. them temporarily.
  227. In addition to the C versions of @code{call-with-blocked-asyncs} and
  228. @code{call-with-unblocked-asyncs}, C code can use
  229. @code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
  230. inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
  231. unblock asyncs temporarily.
  232. @deffn {Scheme Procedure} call-with-blocked-asyncs proc
  233. @deffnx {C Function} scm_call_with_blocked_asyncs (proc)
  234. Call @var{proc} and block the execution of asyncs by one level for the
  235. current thread while it is running. Return the value returned by
  236. @var{proc}. For the first two variants, call @var{proc} with no
  237. arguments; for the third, call it with @var{data}.
  238. @end deffn
  239. @deftypefn {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
  240. The same but with a C function @var{proc} instead of a Scheme thunk.
  241. @end deftypefn
  242. @deffn {Scheme Procedure} call-with-unblocked-asyncs proc
  243. @deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
  244. Call @var{proc} and unblock the execution of asyncs by one level for the
  245. current thread while it is running. Return the value returned by
  246. @var{proc}. For the first two variants, call @var{proc} with no
  247. arguments; for the third, call it with @var{data}.
  248. @end deffn
  249. @deftypefn {C Function} {void *} scm_c_call_with_unblocked_asyncs (void *(*proc) (void *data), void *data)
  250. The same but with a C function @var{proc} instead of a Scheme thunk.
  251. @end deftypefn
  252. @deftypefn {C Function} void scm_dynwind_block_asyncs ()
  253. During the current dynwind context, increase the blocking of asyncs by
  254. one level. This function must be used inside a pair of calls to
  255. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  256. Wind}).
  257. @end deftypefn
  258. @deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
  259. During the current dynwind context, decrease the blocking of asyncs by
  260. one level. This function must be used inside a pair of calls to
  261. @code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
  262. Wind}).
  263. @end deftypefn
  264. Sometimes you want to interrupt a thread that might be waiting for
  265. something to happen, for example on a file descriptor or a condition
  266. variable. In that case you can inform Guile of how to interrupt that
  267. wait using the following procedures:
  268. @deftypefn {C Function} int scm_c_prepare_to_wait_on_fd (int fd)
  269. Inform Guile that the current thread is about to sleep, and that if an
  270. asynchronous interrupt is signalled on this thread, Guile should wake up
  271. the thread by writing a zero byte to @var{fd}. Returns zero if the
  272. prepare succeeded, or nonzero if the thread already has a pending async
  273. and that it should avoid waiting.
  274. @end deftypefn
  275. @deftypefn {C Function} int scm_c_prepare_to_wait_on_cond (scm_i_pthread_mutex_t *mutex, scm_i_pthread_cond_t *cond)
  276. Inform Guile that the current thread is about to sleep, and that if an
  277. asynchronous interrupt is signalled on this thread, Guile should wake up
  278. the thread by acquiring @var{mutex} and signalling @var{cond}. The
  279. caller must already hold @var{mutex} and only drop it as part of the
  280. @code{pthread_cond_wait} call. Returns zero if the prepare succeeded,
  281. or nonzero if the thread already has a pending async and that it should
  282. avoid waiting.
  283. @end deftypefn
  284. @deftypefn {C Function} void scm_c_wait_finished (void)
  285. Inform Guile that the current thread has finished waiting, and that
  286. asynchronous interrupts no longer need any special wakeup action; the
  287. current thread will periodically poll its internal queue instead.
  288. @end deftypefn
  289. Guile's own interface to @code{sleep}, @code{wait-condition-variable},
  290. @code{select}, and so on all call the above routines as appropriate.
  291. Finally, note that threads can also be interrupted via POSIX signals.
  292. @xref{Signals}. As an implementation detail, signal handlers will
  293. effectively call @code{system-async-mark} in a signal-safe way,
  294. eventually running the signal handler using the same async mechanism.
  295. In this way you can temporarily inhibit signal handlers from running
  296. using the above interfaces.
  297. @node Atomics
  298. @subsection Atomics
  299. When accessing data in parallel from multiple threads, updates made by
  300. one thread are not generally guaranteed to be visible by another thread.
  301. It could be that your hardware requires special instructions to be
  302. emitted to propagate a change from one CPU core to another. Or, it
  303. could be that your hardware updates values with a sequence of
  304. instructions, and a parallel thread could see a value that is in the
  305. process of being updated but not fully updated.
  306. Atomic references solve this problem. Atomics are a standard, primitive
  307. facility to allow for concurrent access and update of mutable variables
  308. from multiple threads with guaranteed forward-progress and well-defined
  309. intermediate states.
  310. Atomic references serve not only as a hardware memory barrier but also
  311. as a compiler barrier. Normally a compiler might choose to reorder or
  312. elide certain memory accesses due to optimizations like common
  313. subexpression elimination. Atomic accesses however will not be
  314. reordered relative to each other, and normal memory accesses will not be
  315. reordered across atomic accesses.
  316. As an implementation detail, currently all atomic accesses and updates
  317. use the sequential consistency memory model from C11. We may relax this
  318. in the future to the acquire/release semantics, which still issues a
  319. memory barrier so that non-atomic updates are not reordered across
  320. atomic accesses or updates.
  321. To use Guile's atomic operations, load the @code{(ice-9 atomic)} module:
  322. @example
  323. (use-modules (ice-9 atomic))
  324. @end example
  325. @deffn {Scheme Procedure} make-atomic-box init
  326. Return an atomic box initialized to value @var{init}.
  327. @end deffn
  328. @deffn {Scheme Procedure} atomic-box? obj
  329. Return @code{#t} if @var{obj} is an atomic-box object, else
  330. return @code{#f}.
  331. @end deffn
  332. @deffn {Scheme Procedure} atomic-box-ref box
  333. Fetch the value stored in the atomic box @var{box} and return it.
  334. @end deffn
  335. @deffn {Scheme Procedure} atomic-box-set! box val
  336. Store @var{val} into the atomic box @var{box}.
  337. @end deffn
  338. @deffn {Scheme Procedure} atomic-box-swap! box val
  339. Store @var{val} into the atomic box @var{box}, and return the value that
  340. was previously stored in the box.
  341. @end deffn
  342. @deffn {Scheme Procedure} atomic-box-compare-and-swap! box expected desired
  343. If the value of the atomic box @var{box} is the same as, @var{expected}
  344. (in the sense of @code{eq?}), replace the contents of the box with
  345. @var{desired}. Otherwise does not update the box. Returns the previous
  346. value of the box in either case, so you can know if the swap worked by
  347. checking if the return value is @code{eq?} to @var{expected}.
  348. @end deffn
  349. @node Mutexes and Condition Variables
  350. @subsection Mutexes and Condition Variables
  351. @cindex mutex
  352. @cindex condition variable
  353. Mutexes are low-level primitives used to coordinate concurrent access to
  354. mutable data. Short for ``mutual exclusion'', the name ``mutex''
  355. indicates that only one thread at a time can acquire access to data that
  356. is protected by a mutex -- threads are excluded from accessing data at
  357. the same time. If one thread has locked a mutex, then another thread
  358. attempting to lock that same mutex will wait until the first thread is
  359. done.
  360. Mutexes can be used to build robust multi-threaded programs that take
  361. advantage of multiple cores. However, they provide very low-level
  362. functionality and are somewhat dangerous; usually you end up wanting to
  363. acquire multiple mutexes at the same time to perform a multi-object
  364. access, but this can easily lead to deadlocks if the program is not
  365. carefully written. For example, if objects A and B are protected by
  366. associated mutexes M and N, respectively, then to access both of them
  367. then you need to acquire both mutexes. But what if one thread acquires
  368. M first and then N, at the same time that another thread acquires N them
  369. M? You can easily end up in a situation where one is waiting for the
  370. other.
  371. There's no easy way around this problem on the language level. A
  372. function A that uses mutexes does not necessarily compose nicely with a
  373. function B that uses mutexes. For this reason we suggest using atomic
  374. variables when you can (@pxref{Atomics}), as they do not have this problem.
  375. Still, if you as a programmer are responsible for a whole system, then
  376. you can use mutexes as a primitive to provide safe concurrent
  377. abstractions to your users. (For example, given all locks in a system,
  378. if you establish an order such that M is consistently acquired before N,
  379. you can avoid the ``deadly-embrace'' deadlock described above. The
  380. problem is enumerating all mutexes and establishing this order from a
  381. system perspective.) Guile gives you the low-level facilities to build
  382. such systems.
  383. In Guile there are additional considerations beyond the usual ones in
  384. other programming languages: non-local control flow and asynchronous
  385. interrupts. What happens if you hold a mutex, but somehow you cause an
  386. exception to be thrown? There is no one right answer. You might want
  387. to keep the mutex locked to prevent any other code from ever entering
  388. that critical section again. Or, your critical section might be fine if
  389. you unlock the mutex ``on the way out'', via an exception handler or
  390. @code{dynamic-wind}. @xref{Exceptions}, and @xref{Dynamic Wind}.
  391. But if you arrange to unlock the mutex when leaving a dynamic extent via
  392. @code{dynamic-wind}, what to do if control re-enters that dynamic extent
  393. via a continuation invocation? Surely re-entering the dynamic extent
  394. without the lock is a bad idea, so there are two options on the table:
  395. either prevent re-entry via @code{with-continuation-barrier} or similar,
  396. or reacquire the lock in the entry thunk of a @code{dynamic-wind}.
  397. You might think that because you don't use continuations, that you don't
  398. have to think about this, and you might be right. If you control the
  399. whole system, you can reason about continuation use globally. Or, if
  400. you know all code that can be called in a dynamic extent, and none of
  401. that code can call continuations, then you don't have to worry about
  402. re-entry, and you might not have to worry about early exit either.
  403. However, do consider the possibility of asynchronous interrupts
  404. (@pxref{Asyncs}). If the user interrupts your code interactively, that
  405. can cause an exception; or your thread might be cancelled, which does
  406. the same; or the user could be running your code under some pre-emptive
  407. system that periodically causes lightweight task switching. (Guile does
  408. not currently include such a system, but it's possible to implement as a
  409. library.) Probably you also want to defer asynchronous interrupt
  410. processing while you hold the mutex, and probably that also means that
  411. you should not hold the mutex for very long.
  412. All of these additional Guile-specific considerations mean that from a
  413. system perspective, you would do well to avoid these hazards if you can
  414. by not requiring mutexes. Instead, work with immutable data that can be
  415. shared between threads without hazards, or use persistent data
  416. structures with atomic updates based on the atomic variable library
  417. (@pxref{Atomics}).
  418. There are three types of mutexes in Guile: ``standard'', ``recursive'',
  419. and ``unowned''.
  420. Calling @code{make-mutex} with no arguments makes a standard mutex. A
  421. standard mutex can only be locked once. If you try to lock it again
  422. from the thread that locked it to begin with (the "owner" thread), it
  423. throws an error. It can only be unlocked from the thread that locked it
  424. in the first place.
  425. Calling @code{make-mutex} with the symbol @code{recursive} as the
  426. argument, or calling @code{make-recursive-mutex}, will give you a
  427. recursive mutex. A recursive mutex can be locked multiple times by its
  428. owner. It then has to be unlocked the corresponding number of times,
  429. and like standard mutexes can only be unlocked by the owner thread.
  430. Finally, calling @code{make-mutex} with the symbol
  431. @code{allow-external-unlock} creates an unowned mutex. An unowned mutex
  432. is like a standard mutex, except that it can be unlocked by any thread.
  433. A corollary of this behavior is that a thread's attempt to lock a mutex
  434. that it already owns will block instead of signalling an error, as it
  435. could be that some other thread unlocks the mutex, allowing the owner
  436. thread to proceed. This kind of mutex is a bit strange and is here for
  437. use by SRFI-18.
  438. The mutex procedures in Guile can operate on all three kinds of mutexes.
  439. To use these facilities, load the @code{(ice-9 threads)} module.
  440. @example
  441. (use-modules (ice-9 threads))
  442. @end example
  443. @sp 1
  444. @deffn {Scheme Procedure} make-mutex [kind]
  445. @deffnx {C Function} scm_make_mutex ()
  446. @deffnx {C Function} scm_make_mutex_with_kind (SCM kind)
  447. Return a new mutex. It will be a standard non-recursive mutex, unless
  448. the @code{recursive} symbol is passed as the optional @var{kind}
  449. argument, in which case it will be recursive. It's also possible to
  450. pass @code{unowned} for semantics tailored to SRFI-18's use case; see
  451. above for details.
  452. @end deffn
  453. @deffn {Scheme Procedure} mutex? obj
  454. @deffnx {C Function} scm_mutex_p (obj)
  455. Return @code{#t} if @var{obj} is a mutex; otherwise, return
  456. @code{#f}.
  457. @end deffn
  458. @deffn {Scheme Procedure} make-recursive-mutex
  459. @deffnx {C Function} scm_make_recursive_mutex ()
  460. Create a new recursive mutex. It is initially unlocked. Calling this
  461. function is equivalent to calling @code{make-mutex} with the
  462. @code{recursive} kind.
  463. @end deffn
  464. @deffn {Scheme Procedure} lock-mutex mutex [timeout]
  465. @deffnx {C Function} scm_lock_mutex (mutex)
  466. @deffnx {C Function} scm_timed_lock_mutex (mutex, timeout)
  467. Lock @var{mutex} and return @code{#t}. If the mutex is already locked,
  468. then block and return only when @var{mutex} has been acquired.
  469. When @var{timeout} is given, it specifies a point in time where the
  470. waiting should be aborted. It can be either an integer as returned
  471. by @code{current-time} or a pair as returned by @code{gettimeofday}.
  472. When the waiting is aborted, @code{#f} is returned.
  473. For standard mutexes (@code{make-mutex}), an error is signalled if the
  474. thread has itself already locked @var{mutex}.
  475. For a recursive mutex (@code{make-recursive-mutex}), if the thread has
  476. itself already locked @var{mutex}, then a further @code{lock-mutex}
  477. call increments the lock count. An additional @code{unlock-mutex}
  478. will be required to finally release.
  479. When an asynchronous interrupt (@pxref{Asyncs}) is scheduled for a
  480. thread blocked in @code{lock-mutex}, Guile will interrupt the wait, run
  481. the interrupts, and then resume the wait.
  482. @end deffn
  483. @deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
  484. Arrange for @var{mutex} to be locked whenever the current dynwind
  485. context is entered and to be unlocked when it is exited.
  486. @end deftypefn
  487. @deffn {Scheme Procedure} try-mutex mx
  488. @deffnx {C Function} scm_try_mutex (mx)
  489. Try to lock @var{mutex} and return @code{#t} if successful, or @code{#f}
  490. otherwise. This is like calling @code{lock-mutex} with an expired
  491. timeout.
  492. @end deffn
  493. @deffn {Scheme Procedure} unlock-mutex mutex
  494. @deffnx {C Function} scm_unlock_mutex (mutex)
  495. Unlock @var{mutex}. An error is signalled if @var{mutex} is not locked.
  496. ``Standard'' and ``recursive'' mutexes can only be unlocked by the
  497. thread that locked them; Guile detects this situation and signals an
  498. error. ``Unowned'' mutexes can be unlocked by any thread.
  499. @end deffn
  500. @deffn {Scheme Procedure} mutex-owner mutex
  501. @deffnx {C Function} scm_mutex_owner (mutex)
  502. Return the current owner of @var{mutex}, in the form of a thread or
  503. @code{#f} (indicating no owner). Note that a mutex may be unowned but
  504. still locked.
  505. @end deffn
  506. @deffn {Scheme Procedure} mutex-level mutex
  507. @deffnx {C Function} scm_mutex_level (mutex)
  508. Return the current lock level of @var{mutex}. If @var{mutex} is
  509. currently unlocked, this value will be 0; otherwise, it will be the
  510. number of times @var{mutex} has been recursively locked by its current
  511. owner.
  512. @end deffn
  513. @deffn {Scheme Procedure} mutex-locked? mutex
  514. @deffnx {C Function} scm_mutex_locked_p (mutex)
  515. Return @code{#t} if @var{mutex} is locked, regardless of ownership;
  516. otherwise, return @code{#f}.
  517. @end deffn
  518. @deffn {Scheme Procedure} make-condition-variable
  519. @deffnx {C Function} scm_make_condition_variable ()
  520. Return a new condition variable.
  521. @end deffn
  522. @deffn {Scheme Procedure} condition-variable? obj
  523. @deffnx {C Function} scm_condition_variable_p (obj)
  524. Return @code{#t} if @var{obj} is a condition variable; otherwise,
  525. return @code{#f}.
  526. @end deffn
  527. @deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
  528. @deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
  529. Wait until @var{condvar} has been signalled. While waiting,
  530. @var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
  531. is locked again when this function returns. When @var{time} is given,
  532. it specifies a point in time where the waiting should be aborted. It
  533. can be either a integer as returned by @code{current-time} or a pair
  534. as returned by @code{gettimeofday}. When the waiting is aborted,
  535. @code{#f} is returned. When the condition variable has in fact been
  536. signalled, @code{#t} is returned. The mutex is re-locked in any case
  537. before @code{wait-condition-variable} returns.
  538. When an async is activated for a thread that is blocked in a call to
  539. @code{wait-condition-variable}, the waiting is interrupted, the mutex is
  540. locked, and the async is executed. When the async returns, the mutex is
  541. unlocked again and the waiting is resumed. When the thread block while
  542. re-acquiring the mutex, execution of asyncs is blocked.
  543. @end deffn
  544. @deffn {Scheme Procedure} signal-condition-variable condvar
  545. @deffnx {C Function} scm_signal_condition_variable (condvar)
  546. Wake up one thread that is waiting for @var{condvar}.
  547. @end deffn
  548. @deffn {Scheme Procedure} broadcast-condition-variable condvar
  549. @deffnx {C Function} scm_broadcast_condition_variable (condvar)
  550. Wake up all threads that are waiting for @var{condvar}.
  551. @end deffn
  552. Guile also includes some higher-level abstractions for working with
  553. mutexes.
  554. @deffn macro with-mutex mutex body1 body2 @dots{}
  555. Lock @var{mutex}, evaluate the body @var{body1} @var{body2} @dots{},
  556. then unlock @var{mutex}. The return value is that returned by the last
  557. body form.
  558. The lock, body and unlock form the branches of a @code{dynamic-wind}
  559. (@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
  560. error or new continuation exits the body, and is re-locked if
  561. the body is re-entered by a captured continuation.
  562. @end deffn
  563. @deffn macro monitor body1 body2 @dots{}
  564. Evaluate the body form @var{body1} @var{body2} @dots{} with a mutex
  565. locked so only one thread can execute that code at any one time. The
  566. return value is the return from the last body form.
  567. Each @code{monitor} form has its own private mutex and the locking and
  568. evaluation is as per @code{with-mutex} above. A standard mutex
  569. (@code{make-mutex}) is used, which means the body must not
  570. recursively re-enter the @code{monitor} form.
  571. The term ``monitor'' comes from operating system theory, where it
  572. means a particular bit of code managing access to some resource and
  573. which only ever executes on behalf of one process at any one time.
  574. @end deffn
  575. @node Blocking
  576. @subsection Blocking in Guile Mode
  577. Up to Guile version 1.8, a thread blocked in guile mode would prevent
  578. the garbage collector from running. Thus threads had to explicitly
  579. leave guile mode with @code{scm_without_guile ()} before making a
  580. potentially blocking call such as a mutex lock, a @code{select ()}
  581. system call, etc. The following functions could be used to temporarily
  582. leave guile mode or to perform some common blocking operations in a
  583. supported way.
  584. Starting from Guile 2.0, blocked threads no longer hinder garbage
  585. collection. Thus, the functions below are not needed anymore. They can
  586. still be used to inform the GC that a thread is about to block, giving
  587. it a (small) optimization opportunity for ``stop the world'' garbage
  588. collections, should they occur while the thread is blocked.
  589. @deftypefn {C Function} {void *} scm_without_guile (void *(*func) (void *), void *data)
  590. Leave guile mode, call @var{func} on @var{data}, enter guile mode and
  591. return the result of calling @var{func}.
  592. While a thread has left guile mode, it must not call any libguile
  593. functions except @code{scm_with_guile} or @code{scm_without_guile} and
  594. must not use any libguile macros. Also, local variables of type
  595. @code{SCM} that are allocated while not in guile mode are not
  596. protected from the garbage collector.
  597. When used from non-guile mode, calling @code{scm_without_guile} is
  598. still allowed: it simply calls @var{func}. In that way, you can leave
  599. guile mode without having to know whether the current thread is in
  600. guile mode or not.
  601. @end deftypefn
  602. @deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
  603. Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
  604. the mutex.
  605. @end deftypefn
  606. @deftypefn {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
  607. @deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
  608. Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
  609. leaves guile mode while waiting for the condition variable.
  610. @end deftypefn
  611. @deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
  612. Like @code{select} but leaves guile mode while waiting. Also, the
  613. delivery of an async causes this function to be interrupted with error
  614. code @code{EINTR}.
  615. @end deftypefn
  616. @deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
  617. Like @code{sleep}, but leaves guile mode while sleeping. Also, the
  618. delivery of an async causes this function to be interrupted.
  619. @end deftypefn
  620. @deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
  621. Like @code{usleep}, but leaves guile mode while sleeping. Also, the
  622. delivery of an async causes this function to be interrupted.
  623. @end deftypefn
  624. @node Futures
  625. @subsection Futures
  626. @cindex futures
  627. @cindex fine-grain parallelism
  628. @cindex parallelism
  629. The @code{(ice-9 futures)} module provides @dfn{futures}, a construct
  630. for fine-grain parallelism. A future is a wrapper around an expression
  631. whose computation may occur in parallel with the code of the calling
  632. thread, and possibly in parallel with other futures. Like promises,
  633. futures are essentially proxies that can be queried to obtain the value
  634. of the enclosed expression:
  635. @lisp
  636. (touch (future (+ 2 3)))
  637. @result{} 5
  638. @end lisp
  639. However, unlike promises, the expression associated with a future may be
  640. evaluated on another CPU core, should one be available. This supports
  641. @dfn{fine-grain parallelism}, because even relatively small computations
  642. can be embedded in futures. Consider this sequential code:
  643. @lisp
  644. (define (find-prime lst1 lst2)
  645. (or (find prime? lst1)
  646. (find prime? lst2)))
  647. @end lisp
  648. The two arms of @code{or} are potentially computation-intensive. They
  649. are independent of one another, yet, they are evaluated sequentially
  650. when the first one returns @code{#f}. Using futures, one could rewrite
  651. it like this:
  652. @lisp
  653. (define (find-prime lst1 lst2)
  654. (let ((f (future (find prime? lst2))))
  655. (or (find prime? lst1)
  656. (touch f))))
  657. @end lisp
  658. This preserves the semantics of @code{find-prime}. On a multi-core
  659. machine, though, the computation of @code{(find prime? lst2)} may be
  660. done in parallel with that of the other @code{find} call, which can
  661. reduce the execution time of @code{find-prime}.
  662. Futures may be nested: a future can itself spawn and then @code{touch}
  663. other futures, leading to a directed acyclic graph of futures. Using
  664. this facility, a parallel @code{map} procedure can be defined along
  665. these lines:
  666. @lisp
  667. (use-modules (ice-9 futures) (ice-9 match))
  668. (define (par-map proc lst)
  669. (match lst
  670. (()
  671. '())
  672. ((head tail ...)
  673. (let ((tail (future (par-map proc tail)))
  674. (head (proc head)))
  675. (cons head (touch tail))))))
  676. @end lisp
  677. Note that futures are intended for the evaluation of purely functional
  678. expressions. Expressions that have side-effects or rely on I/O may
  679. require additional care, such as explicit synchronization
  680. (@pxref{Mutexes and Condition Variables}).
  681. Guile's futures are implemented on top of POSIX threads
  682. (@pxref{Threads}). Internally, a fixed-size pool of threads is used to
  683. evaluate futures, such that offloading the evaluation of an expression
  684. to another thread doesn't incur thread creation costs. By default, the
  685. pool contains one thread per available CPU core, minus one, to account
  686. for the main thread. The number of available CPU cores is determined
  687. using @code{current-processor-count} (@pxref{Processes}).
  688. When a thread touches a future that has not completed yet, it processes
  689. any pending future while waiting for it to complete, or just waits if
  690. there are no pending futures. When @code{touch} is called from within a
  691. future, the execution of the calling future is suspended, allowing its
  692. host thread to process other futures, and resumed when the touched
  693. future has completed. This suspend/resume is achieved by capturing the
  694. calling future's continuation, and later reinstating it (@pxref{Prompts,
  695. delimited continuations}).
  696. @deffn {Scheme Syntax} future exp
  697. Return a future for expression @var{exp}. This is equivalent to:
  698. @lisp
  699. (make-future (lambda () exp))
  700. @end lisp
  701. @end deffn
  702. @deffn {Scheme Procedure} make-future thunk
  703. Return a future for @var{thunk}, a zero-argument procedure.
  704. This procedure returns immediately. Execution of @var{thunk} may begin
  705. in parallel with the calling thread's computations, if idle CPU cores
  706. are available, or it may start when @code{touch} is invoked on the
  707. returned future.
  708. If the execution of @var{thunk} throws an exception, that exception will
  709. be re-thrown when @code{touch} is invoked on the returned future.
  710. @end deffn
  711. @deffn {Scheme Procedure} future? obj
  712. Return @code{#t} if @var{obj} is a future.
  713. @end deffn
  714. @deffn {Scheme Procedure} touch f
  715. Return the result of the expression embedded in future @var{f}.
  716. If the result was already computed in parallel, @code{touch} returns
  717. instantaneously. Otherwise, it waits for the computation to complete,
  718. if it already started, or initiates it. In the former case, the calling
  719. thread may process other futures in the meantime.
  720. @end deffn
  721. @node Parallel Forms
  722. @subsection Parallel forms
  723. @cindex parallel forms
  724. The functions described in this section are available from
  725. @example
  726. (use-modules (ice-9 threads))
  727. @end example
  728. They provide high-level parallel constructs. The following functions
  729. are implemented in terms of futures (@pxref{Futures}). Thus they are
  730. relatively cheap as they re-use existing threads, and portable, since
  731. they automatically use one thread per available CPU core.
  732. @deffn syntax parallel expr @dots{}
  733. Evaluate each @var{expr} expression in parallel, each in its own thread.
  734. Return the results of @var{n} expressions as a set of @var{n} multiple
  735. values (@pxref{Multiple Values}).
  736. @end deffn
  737. @deffn syntax letpar ((var expr) @dots{}) body1 body2 @dots{}
  738. Evaluate each @var{expr} in parallel, each in its own thread, then bind
  739. the results to the corresponding @var{var} variables, and then evaluate
  740. @var{body1} @var{body2} @enddots{}
  741. @code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
  742. expressions for the bindings are evaluated in parallel.
  743. @end deffn
  744. @deffn {Scheme Procedure} par-map proc lst1 lst2 @dots{}
  745. @deffnx {Scheme Procedure} par-for-each proc lst1 lst2 @dots{}
  746. Call @var{proc} on the elements of the given lists. @code{par-map}
  747. returns a list comprising the return values from @var{proc}.
  748. @code{par-for-each} returns an unspecified value, but waits for all
  749. calls to complete.
  750. The @var{proc} calls are @code{(@var{proc} @var{elem1} @var{elem2}
  751. @dots{})}, where each @var{elem} is from the corresponding @var{lst} .
  752. Each @var{lst} must be the same length. The calls are potentially made
  753. in parallel, depending on the number of CPU cores available.
  754. These functions are like @code{map} and @code{for-each} (@pxref{List
  755. Mapping}), but make their @var{proc} calls in parallel.
  756. @end deffn
  757. Unlike those above, the functions described below take a number of
  758. threads as an argument. This makes them inherently non-portable since
  759. the specified number of threads may differ from the number of available
  760. CPU cores as returned by @code{current-processor-count}
  761. (@pxref{Processes}). In addition, these functions create the specified
  762. number of threads when they are called and terminate them upon
  763. completion, which makes them quite expensive.
  764. Therefore, they should be avoided.
  765. @deffn {Scheme Procedure} n-par-map n proc lst1 lst2 @dots{}
  766. @deffnx {Scheme Procedure} n-par-for-each n proc lst1 lst2 @dots{}
  767. Call @var{proc} on the elements of the given lists, in the same way as
  768. @code{par-map} and @code{par-for-each} above, but use no more than
  769. @var{n} threads at any one time. The order in which calls are
  770. initiated within that threads limit is unspecified.
  771. These functions are good for controlling resource consumption if
  772. @var{proc} calls might be costly, or if there are many to be made. On
  773. a dual-CPU system for instance @math{@var{n}=4} might be enough to
  774. keep the CPUs utilized, and not consume too much memory.
  775. @end deffn
  776. @deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 lst2 @dots{}
  777. Apply @var{pproc} to the elements of the given lists, and apply
  778. @var{sproc} to each result returned by @var{pproc}. The final return
  779. value is unspecified, but all calls will have been completed before
  780. returning.
  781. The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
  782. @var{elemN}))}, where each @var{elem} is from the corresponding
  783. @var{lst}. Each @var{lst} must have the same number of elements.
  784. The @var{pproc} calls are made in parallel, in separate threads. No more
  785. than @var{n} threads are used at any one time. The order in which
  786. @var{pproc} calls are initiated within that limit is unspecified.
  787. The @var{sproc} calls are made serially, in list element order, one at
  788. a time. @var{pproc} calls on later elements may execute in parallel
  789. with the @var{sproc} calls. Exactly which thread makes each
  790. @var{sproc} call is unspecified.
  791. This function is designed for individual calculations that can be done
  792. in parallel, but with results needing to be handled serially, for
  793. instance to write them to a file. The @var{n} limit on threads
  794. controls system resource usage when there are many calculations or
  795. when they might be costly.
  796. It will be seen that @code{n-for-each-par-map} is like a combination
  797. of @code{n-par-map} and @code{for-each},
  798. @example
  799. (for-each sproc (n-par-map n pproc lst1 ... lstN))
  800. @end example
  801. @noindent
  802. But the actual implementation is more efficient since each @var{sproc}
  803. call, in turn, can be initiated once the relevant @var{pproc} call has
  804. completed, it doesn't need to wait for all to finish.
  805. @end deffn
  806. @c Local Variables:
  807. @c TeX-master: "guile.texi"
  808. @c End: