The mutex and condition variables are described earlier to solve the synchronization problem between threads, and the problem of producer and consumer is solved by using the conditional variable synchronization mechanism.
Let's consider a more complex scenario: the products are different. It is not enough to record only one quantity at this time, but also to record the details of each product. It is easy to think of the need to record these products in a container.
A synchronized, thread-safe queue class is provided in the Python queue module, including FIFO (first-in, first-out) queue Queue,lifo (back-in-first-out) queue Lifoqueue, and priority queue priorityqueue. These queues implement the lock primitive and can be used directly in multiple threads. Queues can be used for synchronization between threads.
The code for implementing the above producer and consumer issues with FIFO queues is as follows:
#Encoding=utf-8ImportThreadingImport Time fromQueueImportQueueclassProducer (Threading. Thread):defRun (self):GlobalQueue Count=0 whileTrue: forIinchRange (100): ifQueue.qsize () > 1000: Pass Else: Count= Count +1msg='Build Product'+Str (count) queue.put (msg)Printmsg Time.sleep (1)classConsumer (Threading. Thread):defRun (self):GlobalQueue whileTrue: forIinchRange (3): ifQueue.qsize () < 100: Pass Else: Msg= Self.name +'consumption of'+Queue.get ()Printmsg Time.sleep (1) Queue=Queue ()defTest (): forIinchRange (500): Queue.put ('Initial Product'+str (i)) forIinchRange (2): P=Producer () P.start ( ) forIinchRange (5): C=Consumer () C.start ( )if __name__=='__main__': Test ()
Python multithreaded Programming (5): Queue synchronization