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.

Semaphore: Python demo

Semaphore: Python demo - Python Tutorial

From the course: Python Parallel and Concurrent Programming Part 2

Start my 1-month free trial

Semaphore: Python demo

- [Instructor] For this Python example, we'll use a counting semaphore to control access to a cell phone charger and keep track of the number of available ports. The semaphore named charger on line eight is initialized to a value of four representing the number of available charging ports. Below that the cell phone function attempts to acquire the chargers semaphore on line 12. If the semaphore is not available because its value is zero then the thread will wait there until a charging port opens up and the semaphore is released. Once a cell phone thread has acquired the semaphore, it prints a message that it's charging and then sleeps for a random amount of time from one to two seconds. After that, the cell phone prints a message that it's all done charging and then releases the semaphore to increment its value so another thread can acquire it. Down in the main section for this program, we use a simple for loop to create and start 10 cell phone threads. I'll switch over to a console…

Contents