How it works...

First, with the producer class, we don't need to pass the integers list because we use the queue to store the integers that are generated.

The thread in the producer class generates integers and puts them in the queue in a for loop. The producer class uses Queue.put(item[, block[, timeout]]) to insert data in the queue. It has the logic to acquire the lock before inserting data in a queue.

There are two possibilities:

  • If the optional arguments block is true and timeout is None (this is the default case that we used in the example), then it is necessary for us to block until a free slot is available. If the timeout is a positive number, then it blocks at most timeout seconds and raises the full exception if no free slot is available within that time.
  • If the block is false, then put an item in the queue if a free slot is immediately available, otherwise, raise the full exception (timeout is ignored in this case). Here, put checks whether the queue is full and then calls wait internally, after which, the producer starts waiting.

Next is the consumer class. The thread gets the integer from the queue and indicates that it is done working on it by using task_done. The consumer class uses Queue.get([block[, timeout]]) and acquires the lock before removing data from the queue. The consumer is placed in a waiting state, in case the queue is empty. Finally, in the main function, we create four threads, one for the producer class and three for the consumer class, respectively.

The output should be like this:

Producer notify : item N°186 appended to queue by Thread-1
Consumer notify : 186 popped from queue by Thread-2

Producer notify : item N°16 appended to queue by Thread-1
Consumer notify : 16 popped from queue by Thread-3

Producer notify : item N°72 appended to queue by Thread-1
Consumer notify : 72 popped from queue by Thread-4

Producer notify : item N°178 appended to queue by Thread-1
Consumer notify : 178 popped from queue by Thread-2

Producer notify : item N°214 appended to queue by Thread-1
Consumer notify : 214 popped from queue by Thread-3

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

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