From the course: Complete Guide to Parallel and Concurrent Programming in Python

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Mutual exclusion: Python demo

Mutual exclusion: Python demo

- [Instructor] To demonstrate how to manually enforce mutual exclusion with locks in Python, we'll modify the example program from earlier with two shoppers that have a data race as they can currently increment the amount of garlic to buy. Locks are included as part of python's threading module, which I've already imported on line 4. So I'll create a new lock object using the constructor method from that module. threading.Lock, and I've assigned it the unimaginative name pencil because Olivia and I used a pencil in our example to serve as a lock. Now to keep the two shopper threads from modifying the garlic_count variable at the same time, I'll call the pencils acquire method before entering the for loop on line 11, and then I'll call its release method immediately after the for loop has finished, pencil.release. I'll save those changes, switch over to the console and run the program. The first shopper thread to begin executing will take the pencil, increment the garlic_count 10…

Contents