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.

Try lock: C++ demo

Try lock: C++ demo - C++ Tutorial

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

Start my 1-month free trial

Try lock: C++ demo

- [Olivia] To demonstrate using try lock in C++, we created this example which simulates two shoppers searching for items they need. And then adding them to a shared notepad. The variable on line eight represents the number of items on the notepad. Within the shopper function, each thread has a local variable declared on line 12 for the number of items to add to the notepad. How many items they found in the coupon book, or perhaps missing from the fridge. The while loop on line 13 will keep the shoppers searching for items and adding them to the notepad until there are at least 20 items. If the shopper has items to add to the notepad, they'll execute the if clause on line 14. In which they lock the pencil mutex, add all their items to the list, and print a message with how many items they've added. That then resets their items to add count back to zero. The thread sleeps for 300 milliseconds to simulate time writing things…

Contents