Review Synchronization, Data Hazards, and Race Conditions
The key challenge of multithreaded programming is knowing how the threads work with shared data. Shared data, also known as resources, are not only variables, but also file descriptors and environment variables, and even Windows registries. For example, if the threads just read the data, then there are no problems and no synchronization is required. However, if at least one of the threads edits the data, race conditions could arise. Usually, the operations on the data are not atomic, that is, they require several steps. Even the simplest increment operation of a numeric variable is performed in the following three steps:
- Read the value of the variable.
- Increment it.
- Write the new value.
Due to the OSes interruptions, the thread can be stopped before it completes the operation. For example, we have threads A and B and have a variable that is equal to 0.
Thread A starts the increment:
- Reads the value of the variable...