Next: , Previous: Blocking, Up: Scheduling


5.17.7 Critical Sections

— C Macro: SCM_CRITICAL_SECTION_START
— C Macro: SCM_CRITICAL_SECTION_END

These two macros can be used to delimit a critical section. Syntactically, they are both statements and need to be followed immediately by a semicolon.

Executing SCM_CRITICAL_SECTION_START will lock a recursive mutex and block the executing of system asyncs. Executing SCM_CRITICAL_SECTION_END will unblock the execution of system asyncs and unlock the mutex. Thus, the code that executes between these two macros can only be executed in one thread at any one time and no system asyncs will run. However, because the mutex is a recursive one, the code might still be reentered by the same thread. You must either allow for this or avoid it, both by careful coding.

On the other hand, critical sections delimited with these macros can be nested since the mutex is recursive.

You must make sure that for each SCM_CRITICAL_SECTION_START, the corresponding SCM_CRITICAL_SECTION_END is always executed. This means that no non-local exit (such as a signalled error) might happen, for example.

— C Function: void scm_dynwind_critical_section (SCM mutex)

Call scm_dynwind_lock_mutex on mutex and call scm_dynwind_block_asyncs. When mutex is false, a recursive mutex provided by Guile is used instead.

The effect of a call to scm_dynwind_critical_section is that the current dynwind context (see Dynamic Wind) turns into a critical section. Because of the locked mutex, no second thread can enter it concurrently and because of the blocked asyncs, no system async can reenter it from the current thread.

When the current thread reenters the critical section anyway, the kind of mutex determines what happens: When mutex is recursive, the reentry is allowed. When it is a normal mutex, an error is signalled.