From the course: Complete Guide to Parallel and Concurrent Programming with C++
Unlock this course with a free trial
Join today to access over 24,800 courses taught by industry experts.
Try lock: C++ demo - C++ Tutorial
From the course: Complete Guide to Parallel and Concurrent Programming with C++
Try lock: C++ demo
- [Instructor] 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 down, and then finally unlocks the pencil on line 20. If the…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.