From the course: Parallel and Concurrent Programming with C++ Part 2

Race condition: C++ demo - C++ Tutorial

From the course: Parallel and Concurrent Programming with C++ Part 2

Start my 1-month free trial

Race condition: C++ demo

- [Instructor] This example demonstrates a race condition with C++ with several threads either adding to or multiplying the value of the bag_of_chips variable on line seven, which represents the number of chips we should buy. The barron_shopper function on line 17 calls the cpu_work function to do a little bit of CPU intensive work before locking the shared mutex, named pencil, then doubling the bags of chips on line 20, and printing a message. These olivia_shopper function below does basically the same thing, except it adds three bags of chips instead of doubling them. Down in the main section, we use a series of for loops to create five barron_shopper threads and five olivia_shopper threads and start them all, wait for them to finish and join, and then finally, print a message with a total number of chips to buy. Notice that both the barron and olivia_shoppers lock the pencil before modifying the shared bag_of_chips variable. Since only one thread can read or write that variable at a time, this program is protected against having a data race, but is still vulnerable to a race condition. To show that, I'll run the program and after all 10 threads finish, it prints a message that we need 125 bags of chips. Now, if I run it again, this time we need 101 bags of chips. The relative order in which the olivia and barron threads were scheduled to add and multiply the bags of chips was different this time, which gave us a different result. Run it again and yet another answer. Again, the problem here is not a data race because we've guaranteed mutual exclusion by having the shoppers lock the pencil before modifying the bags of chips. However, there is a race condition here because the order in which these threads are scheduled to execute changes each time we run the code, which changes the final result.

Contents