From the course: Python Parallel and Concurrent Programming Part 2

Unlock the full course today

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

Race condition: Python demo

Race condition: Python demo - Python Tutorial

From the course: Python Parallel and Concurrent Programming Part 2

Start my 1-month free trial

Race condition: Python demo

- [Instructor] This example demonstrates a race condition in Python with several threads either adding to or multiplying the value of the bags of chips variable on line six which represents the number of chips we should buy for our party. The barron_shopper function on line 14 begins by calling the cpu_work function to simulate doing a but of CPU intensive work. This provides some time for the randomness of the execution scheduler to influence when the shopper threads will get scheduled relative to each other to execute the rest of their code. After completing its CPU work, the barron_shopper acquires the lock named pencil using a context manager on line 17, and then doubles the bags of chips on line 18, and prints a message. The olivia_shopper function below that does basically the same thing except she adds three bags of chips on line 25 instead of doubling them. Down in the main section, we use a series of for loops to create five barron_shopper threads and five olivia_shoppers…

Contents