1, the contradiction between producer and consumer model is the imbalance of data supply and demand
Import TimeImportRandom fromMultiprocessingImportQueue fromMultiprocessingImportProcessdefproducer (Q,food): forIinchRange (5): Q.put ('%s-%s'%(food,i))Print('Production of%s'%Food ) Time.sleep (Random.random ()) q.put (none) Q.put (None) Q.put (none) #有三个消费者因此需要三个信号defConsumer (q,name): whileTrue:food=Q.get ()ifFood = = None: Break Print('%s ate%s'%(Name,food))if __name__=='__main__': Q=Queue () P1= Process (target=producer,args= (q,' Jackfruit dry') ) P1.start () P2= Process (Target=producer, args= (q,' Yogurt') ) P2.start () C1= Process (Target=consumer, args= (q,' RAbbit') ) C1.start () C2= Process (Target=consumer, args= (q,' ORangecat') ) C2.start () C3= Process (Target=consumer, args= (q,' CUihua') ) C3.start ()
Producer Consumer Model
1. How much data the consumer has to deal with is uncertain
2. So the data can only be processed with a while loop, but the while loop cannot end
3. Require the producer to send a signal
4. How many customers need to send a number of signals
5. However, the number of signals sent must be calculated based on the number of producers and consumers, so it is very inconvenient
2,joinablequeue
Import TimeImportRandom fromMultiprocessingImportProcess fromMultiprocessingImportJoinablequeuedefproducer (Q,food): forIinchRange (5): Q.put ('%s-%s'%(food,i))Print('Production of%s'%Food ) Time.sleep (Random.random ()) Q.join ()#waiting for the consumer to finish all the data.defConsumer (q,name): whileTrue:food= Q.get ()#producers are not productive or slow to produce Print('%s ate%s'%(Name,food)) Q.task_done () #Joinablequeue internal count function, each time task_done, Count minus one.
if __name__ = = ' __main__ ':
Q = Joinablequeue ()
P1 = Process (target=producer,args= (q, ' Fried river Powder '))
P1.start ()
P2 = Process (Target=producer, args= (q, ' Strawberry '))
P2.start ()
C1 = Process (Target=consumer, args= (q, ' Rabbit '))
C1.daemon = True
C1.start ()
C2 = Process (Target=consumer, args= (q, ' Orange_cat '))
C2.daemon = True
C2.start ()
C3 = Process (Target=consumer, args= (q, ' Teddy '))
C3.daemon = True
C3.start ()
P1.join () # Wait for P1 to finish executing
P2.join () # Wait for P2 to finish executing
Producer-produced data are all consumed-the end of the producer process-the end of the main process code execution-the end of the consumer daemon process
Python: producer and Consumer models