[From] nickname: HolbrookHttp://www.cnblogs.com/holbrook/archive/2012/02/25/2368231.html
We have introduced the mutex lock and condition variable to solve the synchronization problem between threads, and used the condition variable synchronization mechanism to solve the problem between producers and consumers.
Let's consider a more complex scenario: products are different. At this time, it is not enough to record only one quantity. You also need to record the details of each product. It is easy to think of the need to use a container to record these products.
The queue module of Python provides synchronous and thread-safe queue classes, including FIFO (first-in-first-out) queue, LIFO (first-in-first-out) queue lifoqueue, and priority queue priorityqueue. These queues implement lock primitives and can be used directly in multiple threads. You can use a queue to synchronize threads.
Implement the aforementioned producer and consumer problems using FIFO queuesCodeAs follows:
# Encoding = UTF-8
Import Threading
Import Time
From Queue Import Queue
Class Producer (threading. Thread ):
Def Run (Self ):
Global Queue
Count = 0
While True:
For I In Range (100 ):
If Queue. qsize ()> 1000:
Pass
Else :
Count = count + 1
MSG = ' Generate Product ' + STR (count)
Queue. Put (MSG)
Print MSG
Time. Sleep (1)
Class Consumer (threading. Thread ):
Def Run (Self ):
Global Queue
While True:
For I In Range (3 ):
If Queue. qsize () <100:
Pass
Else :
MSG = self. Name + ' Consumed ' + Queue. Get ()
Print MSG
Time. Sleep (1)
Queue = Queue ()
Def Test ():
For I In Range (500 ):
Queue. Put ( ' Initial Product ' + STR (I ))
For I In Range (2 ):
P = producer ()
P. Start ()
For I In Range (5 ):
C = Consumer ()
C. Start ()
If _ Name __ = ' _ Main __ ' :
Test ()