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

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Data race: C++ demo

Data race: C++ demo - C++ Tutorial

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

Start my 1-month free trial

Data race: C++ demo

- [Instructor] To demonstrate a data race in code, we've created the simple C++ program that uses two threads to concurrently increment a shared variable. The variable on line six is a counter for the amount of garlic we should buy and gets initialized to zero. Below that, the shopper function, defined on line eight, represents a shopper adding garlic to the shopping list. It uses the for loop on line nine to increment the count variable 10 times. Down in the program's main function, starting on line 14, we start two shopper threads called barron and olivia, and then used the join method to wait until they're both done. Finally, we print out the value of the garlic_count variable on line 19, indicating how much garlic we should buy. Switching over to the command prompt, I've already compiled the program, so I'll run it with data_race_demo.exe. The output tells me that we should buy 20 garlic. That makes sense. We have two…

Contents