How to do it...

This solution can be implemented by means of communication strategies between processes, shared memory, or message passing. An incorrect solution could result in a deadlock, in which both processes wait to be awakened:

import multiprocessing
import random
import time

Let's perform the steps as follows:

  1. The producer class is responsible for entering 10 items in the queue by using the put method:
class producer(multiprocessing.Process):
def __init__(self, queue):
multiprocessing.Process.__init__(self)
self.queue = queue

def run(self) :
for i in range(10):
item = random.randint(0, 256)
self.queue.put(item)
print ("Process Producer : item %d appended
to queue %s"
% (item,self.name))
time.sleep(1)
print ("The size of queue is %s"
% self.queue.qsize())
  1. The consumer class has the task of removing the items from the queue (using the get method) and verifying that the queue is not empty. If this happens, then the flow inside the while loop ends with a break statement:
class consumer(multiprocessing.Process):
def __init__(self, queue):
multiprocessing.Process.__init__(self)
self.queue = queue

def run(self):
while True:
if (self.queue.empty()):
print("the queue is empty")
break
else :
time.sleep(2)
item = self.queue.get()
print ('Process Consumer : item %d popped
from by %s '
% (item, self.name))
time.sleep(1)
  1. The multiprocessing class has its queue object instantiated in the main program:
if __name__ == '__main__':
queue = multiprocessing.Queue()
process_producer = producer(queue)
process_consumer = consumer(queue)
process_producer.start()
process_consumer.start()
process_producer.join()
process_consumer.join()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset