Count Synchronization
Count synchronization is necessary because, in all likelihood, the integer increment and decrement operators are not atomic. A compiler must typically generate a non-atomic sequence of instructions to read the count variable, increment it, then write it back. Without synchronization, two different threads could interleave these sequences producing undesirable results, as illustrated in Figure 23.
Figure 23 – Count synchronization execution scenario
The use of the mutex to protect the counter operations ensures that each read-modify-write sequence is not interleaved with counter instruction sequences executing in other threads.