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