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

Unlock the full course today

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

Recursive mutex: C++ demo

Recursive mutex: C++ demo - C++ Tutorial

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

Start my 1-month free trial

Recursive mutex: C++ demo

- [Instructor] To demonstrate using a recursive mutex with C++, we've modified the previous example that we used to demonstrate a data race and mutual exclusion, with two shoppers that concurrently increment the number of items to buy. In this version, we're counting the amount of garlic and potatoes to buy with the variables that are initialized on lines seven and eight. There are two helper functions on lines 11 and 17, called add_garlic and add_potato, which increment the corresponding garlic count or potato count variables, and each of those functions lock and unlock the same mutex, named 'pencil', to enforce mutual exclusion around those operations, and prevent a data race. The shopper function simply uses a for loop on line 24 to execute those add_garlic and add_potato functions 10,000 times each. Down in the program's main function, we create and start two shopper threads, then, after they finish running, we…

Contents