Producer and consumer mode 1. Queue
Advanced First Out
2. Stack
Advanced Post-out
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 primitives (which can be understood as atomic operations, i.e. either not done or done) 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:
ImportThreadingImport Time fromQueueImportQueueclassProducer (Threading. Thread):defRun (self):GlobalQueue Count=0 whileTrue:ifQueue.qsize () < 1000: forIinchRange (100): Count= Count +1msg='Build Product'+Str (count) queue.put (msg)Print(msg) Time.sleep (0.5)classConsumer (Threading. Thread):defRun (self):GlobalQueue whileTrue:ifQueue.qsize () > 100: forIinchRange (3): Msg= Self.name +'consumption of'+Queue.get ()Print(msg) Time.sleep (1)if __name__=='__main__': Queue=Queue () forIinchRange (500): Queue.put ('Initial Product'+str (i)) forIinchRange (2): P=Producer () P.start ( ) forIinchRange (5): C=Consumer () C.start ( )
3. Description of the queue
- For queue, play an important role in multi-threaded communication
- Add data to the queue, use the put () method
- Fetching data from a queue, using the Get () method
- Determine if there is data in the queue, using the Qsize () method
4. Description of the producer consumer model
- Why use producer and consumer models
In the world of threads, the producer is the thread of production data, and the consumer is the thread of consumption data. In multithreaded development, producers have to wait for the consumer to continue producing data if the producer is processing fast and the consumer processing is slow. Similarly, consumers must wait for producers if their processing power is greater than that of producers. To solve this problem, the producer and consumer models were introduced.
- What is the producer consumer model
The producer-consumer model solves the problem of strong coupling between producers and consumers through a container. Producers and consumers do not communicate with each other directly, and through the blocking queue to communicate, so producers do not have to wait for consumer processing after the production of data, directly to the blocking queue, consumers do not find producers to data, but directly from the blocking queue, the blocking queue is equivalent to a buffer, Balance the processing power of producers and consumers.
This blocking queue is used to decouple producers and consumers. Throughout most design patterns, a third party is found to decouple,
Python Producer and Consumer models