Understanding race conditions
A race condition happens when the outcome of running a program depends on the sequence in which its instructions are executed. We will begin with a very simple example to show how race conditions happen, and later in this chapter, we will learn how to resolve this problem.
In the following code, the counter
global variable is incremented by two threads running concurrently:
#include <iostream> #include <thread> int counter = 0; int main() { auto func = [] { for (int i = 0; i < 1000000; ++i) { counter++; } }; std::thread t1(func); std::thread t2(func); t1.join(); t2.join(); std::cout << counter <...