How to do it...

The steps involved are as follows:

  1. The class consumer acquires the shared resource that is modelled through the items[] list:
condition.acquire()
  1. If the length of the list is equal to 0, then the consumer is placed in a waiting state:
if len(items) == 0:
condition.wait()
  1. Then it makes pop operation from the items list:
items.pop()
  1. So, the consumer's state is notified to the producer and the shared resource is released:
condition.notify()
  1. The class producer acquires the shared resource and then it verifies that the list is completely full (in our example, we place the maximum number of items, 10, that can be contained in the items list). If the list is full, then the producer is placed in the wait state until the list is consumed:
condition.acquire()
if len(items) == 10:
condition.wait()
  1. If the list is not full, then a single item is added. The state is notified and the resource is released:
condition.notify()
condition.release()
  1. To show you the condition mechanism, we will use the consumer/producer model again:
import logging
import threading
import time

LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %
(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)

items = []
condition = threading.Condition()


class Consumer(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def consume(self):

with condition:

if len(items) == 0:
logging.info('no items to consume')
condition.wait()

items.pop()
logging.info('consumed 1 item')

condition.notify()

def run(self):
for i in range(20):
time.sleep(2)
self.consume()


class Producer(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def produce(self):

with condition:

if len(items) == 10:
logging.info('items produced {}.
Stopped'.format(len(items)))
condition.wait()

items.append(1)
logging.info('total items {}'.format(len(items)))

condition.notify()

def run(self):
for i in range(20):
time.sleep(0.5)
self.produce()
..................Content has been hidden....................

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