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.
#!/usr/bin/env python#-*-coding:utf-8-*-ImportThreadingImport Time fromQueueImportQueueclassProducer (Threading. Thread):defRun (self):GlobalQueue Count=0 whileTrue: forIinchRange (100): ifQueue.qsize () > 1000: Pass Else: Count+ = 1msg='Build Product'+Str (count) queue.put (count)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 threading Knowledge re-learning f---queue synchronization