Example of race condition
For our second example, we're going to look at a more problematic scenario. Example 15.2, shown in Code Box 15-3, shows just how interleavings happen and how we cannot reliably predict the final output of the example in practice, mainly because of the non-deterministic nature of concurrent systems. The example involves a program that creates three threads at almost the same time, and each of them prints a different string.
The final output of the following code contains the strings printed by three different threads but in an unpredictable order. If the invariant constraint (introduced in the previous chapter) for the following example was to see the strings in a specific order in the output, the following code would have failed at satisfying that constraint, mainly because of the unpredictable interleavings. Let's look at the following code box:
#include <stdio.h> #include <stdlib.h> // The POSIX standard header for using pthread...