THREADS: THREAD
SYNCHRONIZATION
In this chapter, we describe two tools that threads can use to synchronize their
actions: mutexes and condition variables. Mutexes allow threads to synchronize
their use of a shared resource, so that, for example, one thread doesn’t try to access
a shared variable at the same time as another thread is modifying it. Condition vari-
ables perform a complementary task: they allow threads to inform each other that a
shared variable (or other shared resource) has changed state.
30.1 Protecting Accesses to Shared Variables: Mutexes
One of the principal advantages of threads is that they can share information via
global variables. However, this easy sharing comes at a cost: we must take care that
multiple threads do not attempt to modify the same variable at the same time, or
that one thread doesn’t try to read the value of a variable while another thread is
modifying it. The term critical section is used to refer to a section of code that
accesses a shared resource and whose execution should be atomic; that is, its execu-
tion should not be interrupted by another thread that simultaneously accesses the
same shared resource.
Listing 30-1 provides a simple example of the kind of problems that can occur
when shared resources are not accessed atomically. This program creates two
threads, each of which executes the same function. The function executes a loop that
repeatedly increments a global variable, glob, by copying glob into the local variable