Implementing Semaphore
Explore how to implement a semaphore in Python that manages a fixed number of permits allowing concurrent thread access to resources. Understand the use of acquire and release methods guarded by condition variables for safe synchronization and signaling in multithreading scenarios.
We'll cover the following...
Implementing Semaphore
Python does provide its own implementation of Semaphore and BoundedSemaphore, however, we want to implement a semaphore with a slight twist.
Briefly, a semaphore is a construct that allows some threads to access a fixed set of resources in parallel. Always think of a semaphore as having a fixed number of permits to give out. Once all the permits are given out, requesting threads, need to wait for a permit to be returned before proceeding forward.
Your task is to implement a semaphore which takes in its constructor the maximum number of permits allowed and is also initialized with the same number of permits. Additionally, if all the permits have been given out, the semaphore blocks threads attempting to acquire it.
Solution
Given the above definition we can now start to think of what functions our Semaphore class will need to expose. We need a function to "gain the permit" and a function to "return the permit".
acquire()function to simulate gaining a permit