D-Programming-Language/druntime — pull request #204 by alexrp (2012-05-04 04:59:17+00:00)
Title: core.thread: Implement critical regions.

(Not to be confused with critical sections.)

Critical regions are areas of code where a thread absolutely must
not be suspended. Entering and exiting a critical region is very
similar to acquiring and releasing a mutex, but critical regions
do not block. They simply ensure that when the world is stopped,
a thread will not be suspended inside critical code; i.e. it will
be continually suspended and resumed until it is no longer in a
critical region.

This feature is useful to maintain invariants in garbage collectors
where you would normally use a lock. Empirically, it only happens
very rarely that a thread is suspended inside a critical region, so
the suspend/resume loop is a cheaper approach than always locking,
since locking results in high contention.

The way this commit implements critical regions, they are useful
beyond garbage collection, however; they are not specifically
coupled to any GC code.

Using critical regions is extremely error-prone. For instance,
using a lock inside a critical region will most likely result in
an application deadlocking because the stop-the-world routine will
attempt to suspend and resume the thread forever, to no avail.