1. Buffer (which is used as a blocking queue) to solve the problem of strong coupling between consumers and producers. (producers and consumers do not communicate directly) 2. By balancing the producer thread and the consumer thread, the program's overall processing speed is improved. 3. In concurrent programming, this pattern solves most concurrency problems. Example 1. Producers produce once, each consumer consumes once
ImportThreadingImportQueueImportTimedefProducer (): forIinch Range(Ten): Q.put ("Dumplings%s" %IPrint("Start waiting for all the dumplings to be taken away ...")#把操作队列的线程join到生产者线程, after these threads are finished, the producer thread executes further down. Q.join ()Print("All the dumplings are finished ...")defConsumer (N): whileQ.qsize ()>0:Print("%sFetch the %N, Q.get ()) Q.task_done () Time.sleep (1) Q=Queue. Queue () P1=Threading. Thread (target=Producer,) P1.start () P2=Threading. Thread (target=Consumer, args=(' Allen1 ',)) P2.start () P3=Threading. Thread (target=Consumer, args=(' Allen2 ',)) P3.start ()
Example 2. Producers and consumers dynamically generate or consume knowledge points:
- Critical section (locking unlocked)
- Buffer (This example is a blocking queue)
- Producer, Consumer Sync
ImportTime,randomImportQueue,threading#缓冲区用阻塞队列实现Q=Queue. Queue ()a program fragment that #临界区指的是一个访问共用资源 (for example, a shared device or shared memory) that cannot be accessed concurrently by multiple threads#生成全局锁, lock and unlock the shared resource (critical resource) of the bufferLock=Threading. Lock ()defProducer (name):"""producers produce dumplings dynamically in 0-3 seconds """Count= 1 GlobalLock while True: Time.sleep (Random.randrange (3))#生产者线程进入临界区 #修改缓冲区前加锁Lock.acquire ()#缓冲区满, the producer thread is blocked, although the buffer (queue) Here is not set maxsizeQ.put (count, block=True)Print(' Producer%sproduced 1 Jiaozi, has produced%sJiaozi ...%iJiaozi left ' %(Name, Count, Q.qsize ())) Count+=1Lock.release ()#生产者线程退出临界区defConsumer (name):"""consumers in 0-4 seconds dynamic consumption of dumplings """Count= 1 GlobalLock while True: Time.sleep (Random.randrange (4))#消费者线程进入临界区Lock.acquire ()if notQ.empty ():#缓冲区为空, the consumer thread is blocked, although the buffer (queue) Here is not set maxsizeQ.get (Block=True)Print('\033[32;1mconsumer%stook 1 Jiaozi, has taken%sJiaozi ...%iJiaozi Left\033[0m] %(Name, Count, Q.qsize ())) Count+= 1Lock.release ()#消费者线程退出临界区if __name__ == ' __main__ ': P1=Threading. Thread (target=Producer, args=(' P1 ',)) P2=Threading. Thread (target=Producer, args=(' P2 ',)) C1=Threading. Thread (target=Consumer, args=(' C1 ',)) C2=Threading. Thread (target=Consumer, args=(' C2 ',)) P1.start () P2.start () C1.start () C2.start ()
Operating system Os,python-producer consumer model