Implementation of Producer-Consumer Solution using Semaphore
Description: The producer-consumer problem arises when a process is producing some data, the producer, and another process is using that data, the consumer. The producer and the consumer, however, could be operating at different rates, ie the consumer could be using data quicker than the producer can produce it. To support this we need to offer a queue structure for the producer to place data onto and the consumer to take from and also a count of how many items exist on the queue, so producers cannot place too much data on the queue and consumers do not try and take data that is not there.
Since producers and consumers are running at the same time we will use thread. For this, we will import Semaphore, Thread from threading module in Python.
Program:
from threading import Thread, Semaphore
import time
import random
queue = []
MAX_NUM = 10
sem = Semaphore()
class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
while True:
sem.acquire()
if len(queue) == MAX_NUM:
print ("List is full, producer will wait")
sem.release()
print ("Space in queue, Consumer notified the producer")
num = random.choice(nums)
queue.append(num)
print ("Produced", num)
sem.release()
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
while True:
sem.acquire()
if not queue:
print ("List is empty, consumer waiting")
sem.release()
print ("Producer added something to queue and notified the consumer")
num = queue.pop(0)
print ("Consumed", num)
sem.release()
time.sleep(random.random())
def main():
ProducerThread().start()
ConsumerThread().start()
if __name__ == '__main__':
main()
Output:
List is full, producer will wait
Space
Space in queue, Consumer notified the producer
Produced
.....
#this will continue untill keyboard interrupt
Comments