libguile-concepts.texi 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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, 2005, 2010, 2011
  4. @c Free Software Foundation, Inc.
  5. @c See the file guile.texi for copying conditions.
  6. @node General Libguile Concepts
  7. @section General concepts for using libguile
  8. When you want to embed the Guile Scheme interpreter into your program or
  9. library, you need to link it against the @file{libguile} library
  10. (@pxref{Linking Programs With Guile}). Once you have done this, your C
  11. code has access to a number of data types and functions that can be used
  12. to invoke the interpreter, or make new functions that you have written
  13. in C available to be called from Scheme code, among other things.
  14. Scheme is different from C in a number of significant ways, and Guile
  15. tries to make the advantages of Scheme available to C as well. Thus, in
  16. addition to a Scheme interpreter, libguile also offers dynamic types,
  17. garbage collection, continuations, arithmetic on arbitrary sized
  18. numbers, and other things.
  19. The two fundamental concepts are dynamic types and garbage collection.
  20. You need to understand how libguile offers them to C programs in order
  21. to use the rest of libguile. Also, the more general control flow of
  22. Scheme caused by continuations needs to be dealt with.
  23. Running asynchronous signal handlers and multi-threading is known to C
  24. code already, but there are of course a few additional rules when using
  25. them together with libguile.
  26. @menu
  27. * Dynamic Types:: Dynamic Types.
  28. * Garbage Collection:: Garbage Collection.
  29. * Control Flow:: Control Flow.
  30. * Asynchronous Signals:: Asynchronous Signals
  31. * Multi-Threading:: Multi-Threading
  32. @end menu
  33. @node Dynamic Types
  34. @subsection Dynamic Types
  35. Scheme is a dynamically-typed language; this means that the system
  36. cannot, in general, determine the type of a given expression at compile
  37. time. Types only become apparent at run time. Variables do not have
  38. fixed types; a variable may hold a pair at one point, an integer at the
  39. next, and a thousand-element vector later. Instead, values, not
  40. variables, have fixed types.
  41. In order to implement standard Scheme functions like @code{pair?} and
  42. @code{string?} and provide garbage collection, the representation of
  43. every value must contain enough information to accurately determine its
  44. type at run time. Often, Scheme systems also use this information to
  45. determine whether a program has attempted to apply an operation to an
  46. inappropriately typed value (such as taking the @code{car} of a string).
  47. Because variables, pairs, and vectors may hold values of any type,
  48. Scheme implementations use a uniform representation for values --- a
  49. single type large enough to hold either a complete value or a pointer
  50. to a complete value, along with the necessary typing information.
  51. In Guile, this uniform representation of all Scheme values is the C type
  52. @code{SCM}. This is an opaque type and its size is typically equivalent
  53. to that of a pointer to @code{void}. Thus, @code{SCM} values can be
  54. passed around efficiently and they take up reasonably little storage on
  55. their own.
  56. The most important rule is: You never access a @code{SCM} value
  57. directly; you only pass it to functions or macros defined in libguile.
  58. As an obvious example, although a @code{SCM} variable can contain
  59. integers, you can of course not compute the sum of two @code{SCM} values
  60. by adding them with the C @code{+} operator. You must use the libguile
  61. function @code{scm_sum}.
  62. Less obvious and therefore more important to keep in mind is that you
  63. also cannot directly test @code{SCM} values for trueness. In Scheme,
  64. the value @code{#f} is considered false and of course a @code{SCM}
  65. variable can represent that value. But there is no guarantee that the
  66. @code{SCM} representation of @code{#f} looks false to C code as well.
  67. You need to use @code{scm_is_true} or @code{scm_is_false} to test a
  68. @code{SCM} value for trueness or falseness, respectively.
  69. You also can not directly compare two @code{SCM} values to find out
  70. whether they are identical (that is, whether they are @code{eq?} in
  71. Scheme terms). You need to use @code{scm_is_eq} for this.
  72. The one exception is that you can directly assign a @code{SCM} value to
  73. a @code{SCM} variable by using the C @code{=} operator.
  74. The following (contrived) example shows how to do it right. It
  75. implements a function of two arguments (@var{a} and @var{flag}) that
  76. returns @var{a}+1 if @var{flag} is true, else it returns @var{a}
  77. unchanged.
  78. @example
  79. SCM
  80. my_incrementing_function (SCM a, SCM flag)
  81. @{
  82. SCM result;
  83. if (scm_is_true (flag))
  84. result = scm_sum (a, scm_from_int (1));
  85. else
  86. result = a;
  87. return result;
  88. @}
  89. @end example
  90. Often, you need to convert between @code{SCM} values and appropriate C
  91. values. For example, we needed to convert the integer @code{1} to its
  92. @code{SCM} representation in order to add it to @var{a}. Libguile
  93. provides many function to do these conversions, both from C to
  94. @code{SCM} and from @code{SCM} to C.
  95. The conversion functions follow a common naming pattern: those that make
  96. a @code{SCM} value from a C value have names of the form
  97. @code{scm_from_@var{type} (@dots{})} and those that convert a @code{SCM}
  98. value to a C value use the form @code{scm_to_@var{type} (@dots{})}.
  99. However, it is best to avoid converting values when you can. When you
  100. must combine C values and @code{SCM} values in a computation, it is
  101. often better to convert the C values to @code{SCM} values and do the
  102. computation by using libguile functions than to the other way around
  103. (converting @code{SCM} to C and doing the computation some other way).
  104. As a simple example, consider this version of
  105. @code{my_incrementing_function} from above:
  106. @example
  107. SCM
  108. my_other_incrementing_function (SCM a, SCM flag)
  109. @{
  110. int result;
  111. if (scm_is_true (flag))
  112. result = scm_to_int (a) + 1;
  113. else
  114. result = scm_to_int (a);
  115. return scm_from_int (result);
  116. @}
  117. @end example
  118. This version is much less general than the original one: it will only
  119. work for values @var{A} that can fit into a @code{int}. The original
  120. function will work for all values that Guile can represent and that
  121. @code{scm_sum} can understand, including integers bigger than @code{long
  122. long}, floating point numbers, complex numbers, and new numerical types
  123. that have been added to Guile by third-party libraries.
  124. Also, computing with @code{SCM} is not necessarily inefficient. Small
  125. integers will be encoded directly in the @code{SCM} value, for example,
  126. and do not need any additional memory on the heap. See @ref{Data
  127. Representation} to find out the details.
  128. Some special @code{SCM} values are available to C code without needing
  129. to convert them from C values:
  130. @multitable {Scheme value} {C representation}
  131. @item Scheme value @tab C representation
  132. @item @nicode{#f} @tab @nicode{SCM_BOOL_F}
  133. @item @nicode{#t} @tab @nicode{SCM_BOOL_T}
  134. @item @nicode{()} @tab @nicode{SCM_EOL}
  135. @end multitable
  136. In addition to @code{SCM}, Guile also defines the related type
  137. @code{scm_t_bits}. This is an unsigned integral type of sufficient
  138. size to hold all information that is directly contained in a
  139. @code{SCM} value. The @code{scm_t_bits} type is used internally by
  140. Guile to do all the bit twiddling explained in @ref{Data Representation}, but
  141. you will encounter it occasionally in low-level user code as well.
  142. @node Garbage Collection
  143. @subsection Garbage Collection
  144. As explained above, the @code{SCM} type can represent all Scheme values.
  145. Some values fit entirely into a @code{SCM} value (such as small
  146. integers), but other values require additional storage in the heap (such
  147. as strings and vectors). This additional storage is managed
  148. automatically by Guile. You don't need to explicitly deallocate it
  149. when a @code{SCM} value is no longer used.
  150. Two things must be guaranteed so that Guile is able to manage the
  151. storage automatically: it must know about all blocks of memory that have
  152. ever been allocated for Scheme values, and it must know about all Scheme
  153. values that are still being used. Given this knowledge, Guile can
  154. periodically free all blocks that have been allocated but are not used
  155. by any active Scheme values. This activity is called @dfn{garbage
  156. collection}.
  157. It is easy for Guile to remember all blocks of memory that it has
  158. allocated for use by Scheme values, but you need to help it with finding
  159. all Scheme values that are in use by C code.
  160. You do this when writing a SMOB mark function, for example
  161. (@pxref{Garbage Collecting Smobs}). By calling this function, the
  162. garbage collector learns about all references that your SMOB has to
  163. other @code{SCM} values.
  164. Other references to @code{SCM} objects, such as global variables of type
  165. @code{SCM} or other random data structures in the heap that contain
  166. fields of type @code{SCM}, can be made visible to the garbage collector
  167. by calling the functions @code{scm_gc_protect} or
  168. @code{scm_permanent_object}. You normally use these functions for long
  169. lived objects such as a hash table that is stored in a global variable.
  170. For temporary references in local variables or function arguments, using
  171. these functions would be too expensive.
  172. These references are handled differently: Local variables (and function
  173. arguments) of type @code{SCM} are automatically visible to the garbage
  174. collector. This works because the collector scans the stack for
  175. potential references to @code{SCM} objects and considers all referenced
  176. objects to be alive. The scanning considers each and every word of the
  177. stack, regardless of what it is actually used for, and then decides
  178. whether it could possibly be a reference to a @code{SCM} object. Thus,
  179. the scanning is guaranteed to find all actual references, but it might
  180. also find words that only accidentally look like references. These
  181. `false positives' might keep @code{SCM} objects alive that would
  182. otherwise be considered dead. While this might waste memory, keeping an
  183. object around longer than it strictly needs to is harmless. This is why
  184. this technique is called ``conservative garbage collection''. In
  185. practice, the wasted memory seems to be no problem.
  186. The stack of every thread is scanned in this way and the registers of
  187. the CPU and all other memory locations where local variables or function
  188. parameters might show up are included in this scan as well.
  189. The consequence of the conservative scanning is that you can just
  190. declare local variables and function parameters of type @code{SCM} and
  191. be sure that the garbage collector will not free the corresponding
  192. objects.
  193. However, a local variable or function parameter is only protected as
  194. long as it is really on the stack (or in some register). As an
  195. optimization, the C compiler might reuse its location for some other
  196. value and the @code{SCM} object would no longer be protected. Normally,
  197. this leads to exactly the right behavior: the compiler will only
  198. overwrite a reference when it is no longer needed and thus the object
  199. becomes unprotected precisely when the reference disappears, just as
  200. wanted.
  201. There are situations, however, where a @code{SCM} object needs to be
  202. around longer than its reference from a local variable or function
  203. parameter. This happens, for example, when you retrieve some pointer
  204. from a smob and work with that pointer directly. The reference to the
  205. @code{SCM} smob object might be dead after the pointer has been
  206. retrieved, but the pointer itself (and the memory pointed to) is still
  207. in use and thus the smob object must be protected. The compiler does
  208. not know about this connection and might overwrite the @code{SCM}
  209. reference too early.
  210. To get around this problem, you can use @code{scm_remember_upto_here_1}
  211. and its cousins. It will keep the compiler from overwriting the
  212. reference. For a typical example of its use, see @ref{Remembering
  213. During Operations}.
  214. @node Control Flow
  215. @subsection Control Flow
  216. Scheme has a more general view of program flow than C, both locally and
  217. non-locally.
  218. Controlling the local flow of control involves things like gotos, loops,
  219. calling functions and returning from them. Non-local control flow
  220. refers to situations where the program jumps across one or more levels
  221. of function activations without using the normal call or return
  222. operations.
  223. The primitive means of C for local control flow is the @code{goto}
  224. statement, together with @code{if}. Loops done with @code{for},
  225. @code{while} or @code{do} could in principle be rewritten with just
  226. @code{goto} and @code{if}. In Scheme, the primitive means for local
  227. control flow is the @emph{function call} (together with @code{if}).
  228. Thus, the repetition of some computation in a loop is ultimately
  229. implemented by a function that calls itself, that is, by recursion.
  230. This approach is theoretically very powerful since it is easier to
  231. reason formally about recursion than about gotos. In C, using
  232. recursion exclusively would not be practical, though, since it would eat
  233. up the stack very quickly. In Scheme, however, it is practical:
  234. function calls that appear in a @dfn{tail position} do not use any
  235. additional stack space (@pxref{Tail Calls}).
  236. A function call is in a tail position when it is the last thing the
  237. calling function does. The value returned by the called function is
  238. immediately returned from the calling function. In the following
  239. example, the call to @code{bar-1} is in a tail position, while the
  240. call to @code{bar-2} is not. (The call to @code{1-} in @code{foo-2}
  241. is in a tail position, though.)
  242. @lisp
  243. (define (foo-1 x)
  244. (bar-1 (1- x)))
  245. (define (foo-2 x)
  246. (1- (bar-2 x)))
  247. @end lisp
  248. Thus, when you take care to recurse only in tail positions, the
  249. recursion will only use constant stack space and will be as good as a
  250. loop constructed from gotos.
  251. Scheme offers a few syntactic abstractions (@code{do} and @dfn{named}
  252. @code{let}) that make writing loops slightly easier.
  253. But only Scheme functions can call other functions in a tail position:
  254. C functions can not. This matters when you have, say, two functions
  255. that call each other recursively to form a common loop. The following
  256. (unrealistic) example shows how one might go about determining whether a
  257. non-negative integer @var{n} is even or odd.
  258. @lisp
  259. (define (my-even? n)
  260. (cond ((zero? n) #t)
  261. (else (my-odd? (1- n)))))
  262. (define (my-odd? n)
  263. (cond ((zero? n) #f)
  264. (else (my-even? (1- n)))))
  265. @end lisp
  266. Because the calls to @code{my-even?} and @code{my-odd?} are in tail
  267. positions, these two procedures can be applied to arbitrary large
  268. integers without overflowing the stack. (They will still take a lot
  269. of time, of course.)
  270. However, when one or both of the two procedures would be rewritten in
  271. C, it could no longer call its companion in a tail position (since C
  272. does not have this concept). You might need to take this
  273. consideration into account when deciding which parts of your program
  274. to write in Scheme and which in C.
  275. In addition to calling functions and returning from them, a Scheme
  276. program can also exit non-locally from a function so that the control
  277. flow returns directly to an outer level. This means that some functions
  278. might not return at all.
  279. Even more, it is not only possible to jump to some outer level of
  280. control, a Scheme program can also jump back into the middle of a
  281. function that has already exited. This might cause some functions to
  282. return more than once.
  283. In general, these non-local jumps are done by invoking
  284. @dfn{continuations} that have previously been captured using
  285. @code{call-with-current-continuation}. Guile also offers a slightly
  286. restricted set of functions, @code{catch} and @code{throw}, that can
  287. only be used for non-local exits. This restriction makes them more
  288. efficient. Error reporting (with the function @code{error}) is
  289. implemented by invoking @code{throw}, for example. The functions
  290. @code{catch} and @code{throw} belong to the topic of @dfn{exceptions}.
  291. Since Scheme functions can call C functions and vice versa, C code can
  292. experience the more general control flow of Scheme as well. It is
  293. possible that a C function will not return at all, or will return more
  294. than once. While C does offer @code{setjmp} and @code{longjmp} for
  295. non-local exits, it is still an unusual thing for C code. In
  296. contrast, non-local exits are very common in Scheme, mostly to report
  297. errors.
  298. You need to be prepared for the non-local jumps in the control flow
  299. whenever you use a function from @code{libguile}: it is best to assume
  300. that any @code{libguile} function might signal an error or run a pending
  301. signal handler (which in turn can do arbitrary things).
  302. It is often necessary to take cleanup actions when the control leaves a
  303. function non-locally. Also, when the control returns non-locally, some
  304. setup actions might be called for. For example, the Scheme function
  305. @code{with-output-to-port} needs to modify the global state so that
  306. @code{current-output-port} returns the port passed to
  307. @code{with-output-to-port}. The global output port needs to be reset to
  308. its previous value when @code{with-output-to-port} returns normally or
  309. when it is exited non-locally. Likewise, the port needs to be set again
  310. when control enters non-locally.
  311. Scheme code can use the @code{dynamic-wind} function to arrange for
  312. the setting and resetting of the global state. C code can use the
  313. corresponding @code{scm_internal_dynamic_wind} function, or a
  314. @code{scm_dynwind_begin}/@code{scm_dynwind_end} pair together with
  315. suitable 'dynwind actions' (@pxref{Dynamic Wind}).
  316. Instead of coping with non-local control flow, you can also prevent it
  317. by erecting a @emph{continuation barrier}, @xref{Continuation
  318. Barriers}. The function @code{scm_c_with_continuation_barrier}, for
  319. example, is guaranteed to return exactly once.
  320. @node Asynchronous Signals
  321. @subsection Asynchronous Signals
  322. You can not call libguile functions from handlers for POSIX signals, but
  323. you can register Scheme handlers for POSIX signals such as
  324. @code{SIGINT}. These handlers do not run during the actual signal
  325. delivery. Instead, they are run when the program (more precisely, the
  326. thread that the handler has been registered for) reaches the next
  327. @emph{safe point}.
  328. The libguile functions themselves have many such safe points.
  329. Consequently, you must be prepared for arbitrary actions anytime you
  330. call a libguile function. For example, even @code{scm_cons} can contain
  331. a safe point and when a signal handler is pending for your thread,
  332. calling @code{scm_cons} will run this handler and anything might happen,
  333. including a non-local exit although @code{scm_cons} would not ordinarily
  334. do such a thing on its own.
  335. If you do not want to allow the running of asynchronous signal handlers,
  336. you can block them temporarily with @code{scm_dynwind_block_asyncs}, for
  337. example. See @xref{System asyncs}.
  338. Since signal handling in Guile relies on safe points, you need to make
  339. sure that your functions do offer enough of them. Normally, calling
  340. libguile functions in the normal course of action is all that is needed.
  341. But when a thread might spent a long time in a code section that calls
  342. no libguile function, it is good to include explicit safe points. This
  343. can allow the user to interrupt your code with @key{C-c}, for example.
  344. You can do this with the macro @code{SCM_TICK}. This macro is
  345. syntactically a statement. That is, you could use it like this:
  346. @example
  347. while (1)
  348. @{
  349. SCM_TICK;
  350. do_some_work ();
  351. @}
  352. @end example
  353. Frequent execution of a safe point is even more important in multi
  354. threaded programs, @xref{Multi-Threading}.
  355. @node Multi-Threading
  356. @subsection Multi-Threading
  357. Guile can be used in multi-threaded programs just as well as in
  358. single-threaded ones.
  359. Each thread that wants to use functions from libguile must put itself
  360. into @emph{guile mode} and must then follow a few rules. If it doesn't
  361. want to honor these rules in certain situations, a thread can
  362. temporarily leave guile mode (but can no longer use libguile functions
  363. during that time, of course).
  364. Threads enter guile mode by calling @code{scm_with_guile},
  365. @code{scm_boot_guile}, or @code{scm_init_guile}. As explained in the
  366. reference documentation for these functions, Guile will then learn about
  367. the stack bounds of the thread and can protect the @code{SCM} values
  368. that are stored in local variables. When a thread puts itself into
  369. guile mode for the first time, it gets a Scheme representation and is
  370. listed by @code{all-threads}, for example.
  371. Threads in guile mode can block (e.g., do blocking I/O) without causing
  372. any problems@footnote{In Guile 1.8, a thread blocking in guile mode
  373. would prevent garbage collection to occur. Thus, threads had to leave
  374. guile mode whenever they could block. This is no longer needed with
  375. Guile 2.@var{x}.}; temporarily leaving guile mode with
  376. @code{scm_without_guile} before blocking slightly improves GC
  377. performance, though. For some common blocking operations, Guile
  378. provides convenience functions. For example, if you want to lock a
  379. pthread mutex while in guile mode, you might want to use
  380. @code{scm_pthread_mutex_lock} which is just like
  381. @code{pthread_mutex_lock} except that it leaves guile mode while
  382. blocking.
  383. All libguile functions are (intended to be) robust in the face of
  384. multiple threads using them concurrently. This means that there is no
  385. risk of the internal data structures of libguile becoming corrupted in
  386. such a way that the process crashes.
  387. A program might still produce nonsensical results, though. Taking
  388. hashtables as an example, Guile guarantees that you can use them from
  389. multiple threads concurrently and a hashtable will always remain a valid
  390. hashtable and Guile will not crash when you access it. It does not
  391. guarantee, however, that inserting into it concurrently from two threads
  392. will give useful results: only one insertion might actually happen, none
  393. might happen, or the table might in general be modified in a totally
  394. arbitrary manner. (It will still be a valid hashtable, but not the one
  395. that you might have expected.) Guile might also signal an error when it
  396. detects a harmful race condition.
  397. Thus, you need to put in additional synchronizations when multiple
  398. threads want to use a single hashtable, or any other mutable Scheme
  399. object.
  400. When writing C code for use with libguile, you should try to make it
  401. robust as well. An example that converts a list into a vector will help
  402. to illustrate. Here is a correct version:
  403. @example
  404. SCM
  405. my_list_to_vector (SCM list)
  406. @{
  407. SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED);
  408. size_t len, i;
  409. len = SCM_SIMPLE_VECTOR_LENGTH (vector);
  410. i = 0;
  411. while (i < len && scm_is_pair (list))
  412. @{
  413. SCM_SIMPLE_VECTOR_SET (vector, i, SCM_CAR (list));
  414. list = SCM_CDR (list);
  415. i++;
  416. @}
  417. return vector;
  418. @}
  419. @end example
  420. The first thing to note is that storing into a @code{SCM} location
  421. concurrently from multiple threads is guaranteed to be robust: you don't
  422. know which value wins but it will in any case be a valid @code{SCM}
  423. value.
  424. But there is no guarantee that the list referenced by @var{list} is not
  425. modified in another thread while the loop iterates over it. Thus, while
  426. copying its elements into the vector, the list might get longer or
  427. shorter. For this reason, the loop must check both that it doesn't
  428. overrun the vector (@code{SCM_SIMPLE_VECTOR_SET} does no range-checking)
  429. and that it doesn't overrun the list (@code{SCM_CAR} and @code{SCM_CDR}
  430. likewise do no type checking).
  431. It is safe to use @code{SCM_CAR} and @code{SCM_CDR} on the local
  432. variable @var{list} once it is known that the variable contains a pair.
  433. The contents of the pair might change spontaneously, but it will always
  434. stay a valid pair (and a local variable will of course not spontaneously
  435. point to a different Scheme object).
  436. Likewise, a simple vector such as the one returned by
  437. @code{scm_make_vector} is guaranteed to always stay the same length so
  438. that it is safe to only use SCM_SIMPLE_VECTOR_LENGTH once and store the
  439. result. (In the example, @var{vector} is safe anyway since it is a
  440. fresh object that no other thread can possibly know about until it is
  441. returned from @code{my_list_to_vector}.)
  442. Of course the behavior of @code{my_list_to_vector} is suboptimal when
  443. @var{list} does indeed get asynchronously lengthened or shortened in
  444. another thread. But it is robust: it will always return a valid vector.
  445. That vector might be shorter than expected, or its last elements might
  446. be unspecified, but it is a valid vector and if a program wants to rule
  447. out these cases, it must avoid modifying the list asynchronously.
  448. Here is another version that is also correct:
  449. @example
  450. SCM
  451. my_pedantic_list_to_vector (SCM list)
  452. @{
  453. SCM vector = scm_make_vector (scm_length (list), SCM_UNDEFINED);
  454. size_t len, i;
  455. len = SCM_SIMPLE_VECTOR_LENGTH (vector);
  456. i = 0;
  457. while (i < len)
  458. @{
  459. SCM_SIMPLE_VECTOR_SET (vector, i, scm_car (list));
  460. list = scm_cdr (list);
  461. i++;
  462. @}
  463. return vector;
  464. @}
  465. @end example
  466. This version uses the type-checking and thread-robust functions
  467. @code{scm_car} and @code{scm_cdr} instead of the faster, but less robust
  468. macros @code{SCM_CAR} and @code{SCM_CDR}. When the list is shortened
  469. (that is, when @var{list} holds a non-pair), @code{scm_car} will throw
  470. an error. This might be preferable to just returning a half-initialized
  471. vector.
  472. The API for accessing vectors and arrays of various kinds from C takes a
  473. slightly different approach to thread-robustness. In order to get at
  474. the raw memory that stores the elements of an array, you need to
  475. @emph{reserve} that array as long as you need the raw memory. During
  476. the time an array is reserved, its elements can still spontaneously
  477. change their values, but the memory itself and other things like the
  478. size of the array are guaranteed to stay fixed. Any operation that
  479. would change these parameters of an array that is currently reserved
  480. will signal an error. In order to avoid these errors, a program should
  481. of course put suitable synchronization mechanisms in place. As you can
  482. see, Guile itself is again only concerned about robustness, not about
  483. correctness: without proper synchronization, your program will likely
  484. not be correct, but the worst consequence is an error message.
  485. Real thread-safeness often requires that a critical section of code is
  486. executed in a certain restricted manner. A common requirement is that
  487. the code section is not entered a second time when it is already being
  488. executed. Locking a mutex while in that section ensures that no other
  489. thread will start executing it, blocking asyncs ensures that no
  490. asynchronous code enters the section again from the current thread,
  491. and the error checking of Guile mutexes guarantees that an error is
  492. signalled when the current thread accidentally reenters the critical
  493. section via recursive function calls.
  494. Guile provides two mechanisms to support critical sections as outlined
  495. above. You can either use the macros
  496. @code{SCM_CRITICAL_SECTION_START} and @code{SCM_CRITICAL_SECTION_END}
  497. for very simple sections; or use a dynwind context together with a
  498. call to @code{scm_dynwind_critical_section}.
  499. The macros only work reliably for critical sections that are
  500. guaranteed to not cause a non-local exit. They also do not detect an
  501. accidental reentry by the current thread. Thus, you should probably
  502. only use them to delimit critical sections that do not contain calls
  503. to libguile functions or to other external functions that might do
  504. complicated things.
  505. The function @code{scm_dynwind_critical_section}, on the other hand,
  506. will correctly deal with non-local exits because it requires a dynwind
  507. context. Also, by using a separate mutex for each critical section,
  508. it can detect accidental reentries.