Avoiding race conditions with mutexes
A mutex is a locking mechanism that prevents access to a shared variable so that no more than one thread can access it simultaneously. This prevents race conditions. With a mutex, we only lock the critical part of the code, for example, the updating of a shared variable. This will make sure that all other parts of the program run in parallel (if this is possible with the locking mechanism).
However, if we are not careful when we write our programs, a mutex can slow down the program a lot, which we'll see in this recipe. In the next recipe, we'll fix this problem.
Knowing how to use mutexes will help you overcome many of the problems associated with race conditions, making your programs safer and better.
Getting ready
In order for this recipe to make sense, it's advised that you complete the previous recipe first. You'll also need the Makefile that we wrote in the first recipe of this chapter, the GCC compiler, and...