From the course: Complete Guide to Parallel and Concurrent Programming in Python
Unlock this course with a free trial
Join today to access over 25,300 courses taught by industry experts.
Race condition: Python demo - Python Tutorial
From the course: Complete Guide to Parallel and Concurrent Programming in Python
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 6, 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 bit 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…
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.