This is the problem of the buffer of maximum size. Producer cannot produce if the buffer is full and the consumer needs to wait if the buffer is empty. Apparently, this solution using semaphores work only for single producer and consumer. Can somebody explain me why it doesnot work for multiple producers and consumers?
has_space = Semaphore(max_num)
has_elements = Semaphore(0)
mutex = lock()
def producer():
has_space.acquire()
with mutex:
# add elements
has_elements.release()
def consumer():
has_elements.acquire()
with mutex:
# retrieve elements
has_space.release()
Your example experiences race conditions. You really need something along the lines of condition variables. There is no way using just semaphores to ensure that multiple producers are not writing to a full buffer or that multiple consumers are not reading from an empty buffer.
The single producer, single consumer model simply blocks the consumer until the producer acts, then blocks the producer until the consumer acts. There is no indication if the shared buffer is empty or full. Note that the semaphore count is not the same as the full or empty condition of the buffer.