From the course: Complete Guide to Parallel and Concurrent Programming with C++

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Recursive mutex: C++ demo

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 print out the amount of garlic and potatoes to buy. Running this program as is…

Contents