Producer Consumer: Bun shop keeps making steamed buns, pedestrians keep buying---> so to achieve the purpose---> Bun sales
Two different characters Bun shop, pedestrians only responsible for a single operation to make the bun into a connected medium.
1 #_*_coding:utf-8_*_2 fromThreadingImportThread3 fromQueueImportQueue4 Import Time5 classProcuder (Thread):6 def __init__(self,name,queue):7Self.__name=name8Self.__queue=Queue9Super (Procuder,self).__init__()Ten defRun (self): One while1: A ifSelf.__queue. Full (): -Time.sleep (3) - Else: theTime.sleep (1) -Self.__queue. put ('**star**') - Print '-->%s plus a star'% self.__name - classCunsumer (Thread): + def __init__(self,name,queue): -Self.__name=name +Self.__queue=Queue ASuper (Cunsumer,self).__init__() at defRun (self): - while1: - ifSelf.__queue. Empty (): -Time.sleep (3) - Else: -Time.sleep (1) inSelf.__queue. Get () - Print '-->%s get a star'% self.__name toMaxque = Queue (maxsize=50) + -P1 = Procuder ('P1', Maxque) the P1.start () *P2 = Procuder ('P2', Maxque) $ P2.start ()Panax NotoginsengP3 = Procuder ('P3', Maxque) - P3.start () the forIinchRange (20): + Print '_________________' Atemp =Cunsumer (I,maxque) theTemp.start ()
So the question comes---> Why do we need this model?
1 decoupling: The core is to make the relationship between the producer and the consumer not close to the two objects
2 buffer: If you are a courier, send a lot of people's buildings, you think it is sent to the front desk, send a text message let them to take it?
3 Prevent blocking: or the above example, if you are one by one send so if there is a person 30 minutes to take you are not to wait 30 minutes?
Python-implementing a producer consumer model