From the course: Python Parallel and Concurrent Programming Part 1

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Mutual exclusion: Python demo

Mutual exclusion: Python demo - Python Tutorial

From the course: Python Parallel and Concurrent Programming Part 1

Start my 1-month free trial

Mutual exclusion: Python demo

- 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 four. So, I'll create a new lock object using the constructor method from that module. Threading dot 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 pencil's acquire method before entering the for loop on line eleven and then I'll call its release method immediately after the for loop has finished. Pencil dot release. I'll save those changes, switch over to the console and run the program. The first shopper thread to…

Contents