How to do it...

The following code describes a problem where we have two threads, producer() and consumer(), that share a common resource, which is the item. The task of producer() is to generate the item while the consumer() thread's task is to use the item that has been produced.

If the item has not yet produced the consumer() thread, then it has to wait. As soon as the item is produced, the producer() thread notifies the consumer that the resource should be used:

  1. By initializing a semaphore to 0, we obtain a so-called semaphore event whose sole purpose is to synchronize the computation of two or more threads. Here, a thread must make use of data or common resources simultaneously:
semaphore = threading.Semaphore(0)
  1. This operation is very similar to that described in the lock mechanism of the lock. The producer() thread creates the item and, after that, it frees the resource by calling the release() method:
semaphore.release()
  1. Similarly, the consumer() thread acquires the data by the acquire() method. If the semaphore's counter is equal to 0, then it blocks the condition's acquire() method until it gets notified by a different thread. If the semaphore's counter is greater than 0, then it decrements the value. When the producer creates an item, it releases the semaphore, and then the consumer acquires it and consumes the shared resource:
semaphore.acquire()
  1. The synchronization process that is done via the semaphores is shown in the following code block:
import logging
import threading
import time
import random

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

semaphore = threading.Semaphore(0)
item = 0

def consumer():
logging.info('Consumer is waiting')
semaphore.acquire()
logging.info('Consumer notify: item number {}'.format(item))

def producer():
global item
time.sleep(3)
item = random.randint(0, 1000)
logging.info('Producer notify: item number {}'.format(item))
semaphore.release()

#Main program
def main():
for i in range(10):
t1 = threading.Thread(target=consumer)
t2 = threading.Thread(target=producer)

t1.start()
t2.start()

t1.join()
t2.join()

if __name__ == "__main__":
main()
..................Content has been hidden....................

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