Investigate how to prevent a data race by adding a mutex to the previous example C++ program. Observe that by enforcing mutual exclusion in the critical section the program produces a deterministic result. In this video, learn about how to use a mutex to prevent data races in C++ programs.
- [Instructor] To demonstrate how to manually enforce … mutual exclusion with a Mutex, … we'll modify the example program from earlier … with two shopper's that have a data race, … as it can currently increment the amount of garlic to buy. … Before creating a Mutex, … I'll need to include the Mutex header in this program. … Now, I'll create a new Mutex, and because Barron and I … used the pencil for our Mutex, … I'll give it the creative name of pencil. … To keep the two shopper threads from modifying … the garlic count and variable at the same time, … I'll call the pencil Mutexes Lock Number function … to acquire the lock on it … before entering the for-loop on line 11. … And, I'll call its unlock method after the for-loop … completes, to release the hold on it. … Switching over to the command prompt, … I'll build that program with a Make Command … and then run it. … The first shopper thread to begin executing … will take the pencil, increment the garlic count … 10 million times and then unlock the pencil …
- Parallel computing architectures
- Shared vs. distributed memory
- Thread vs. process
- Execution scheduling
- The thread lifecycle in C++
- Mutual exclusion
- Locking in recursive and shared mutexes
- Acquiring a lock on a mutex with a try lock
- Resolving deadlock and livelock conditions
Skill Level Advanced
1. Parallel Computing Hardware
2. Threads and Processes
3. Mutual Exclusion
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.