How to do it...

Again, to explain how to synchronize threads through events, we will refer to the producer/consumer problem. The problem describes two processes, a producer and a consumer, who share a common buffer of a fixed size. The producer's task is to generate items and deposit them in the continuous buffer. At the same time, the consumer will use the items produced, removing them from the buffer from time to time.

The problem is to ensure that the producer does not process new data if the buffer is full and that the consumer does not look for data if the buffer is empty.

Now, let's see how to implement the consumer/producer problem by using thread synchronization with an event statement:

  1. Here, the relevant libraries are imported as follows:
import logging
import threading
import time
import random
  1. Then, we define the log output format. It is useful to clearly visualize what's happening:
LOG_FORMAT = '%(asctime)s %(threadName)-17s %(levelname)-8s %
(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
  1. Set the items list. This parameter will be used by the Consumer and Producer classes:
items = []
  1. The event parameter is defined as follows. This parameter will be used to synchronize the communication between threads:
event = threading.Event()
  1. The Consumer class is initialized with the list of items and the Event() function. In the run method, the consumer waits for a new item to consume. When the item arrives, it is popped from the item list:
class Consumer(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

def run(self):
while True:
time.sleep(2)
event.wait()
item = items.pop()
logging.info('Consumer notify: {} popped by {}'
.format(item, self.name))
  1. The Producer class is initialized with the list of items and the Event() function. Unlike the example with condition objects, the item list is not global, but it is passed as a parameter:
class Producer(threading.Thread):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
  1. In the run method for each item that is created, the Producer class appends it to the list of items and then notifies the event:
    def run(self):
for i in range(5):
time.sleep(2)
item = random.randint(0, 100)
items.append(item)
logging.info('Producer notify: item {} appended by
{}'.format(item, self.name))
  1. There are two steps that you need to take for this and the first step, which are as follows:
            event.set()
event.clear()
  1. The t1 thread appends a value to the list and then sets the event to notify the consumer. The consumer's call to wait() stops blocking and the integer is retrieved from the list:
if __name__ == "__main__":
t1 = Producer()
t2 = Consumer()

t1.start()
t2.start()

t1.join()
t2.join()

..................Content has been hidden....................

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