Causing a race condition
A race condition is when more than one thread (or process) tries to write to the same variable simultaneously. Since we don't know which thread will access the variable first, we can't safely predict what will happen. Both threads will try to access it first; they will race to access the variable.
Knowing what's causing a race condition will help you avoid them, making your programs safer.
Getting ready
For this recipe, you'll only need the Makefile we wrote in the first recipe of this chapter, along with the GCC compiler and the Make tool.
How to do it…
In this recipe, we'll write a program that causes a race condition. If the program were to work properly, it should add 1 to the i
variable on every run, ending up at 5,000,000,000. There are five threads, and each thread adds 1 up to 1,000,000,000. But since all the threads access the i
variable simultaneously—more or less—it never reaches 5,000...