Producer consumers are using a container to solve the problem of strong coupling between producers and consumers. Producers and consumers do not communicate directly, but by blocking the queue. The blocking queue is quite a buffer, balancing the processing power of producers and consumers.
ImportTime,randomImportQueue,threadingq=queue. Queue ()defProducer (name): Count=0 whileCount <10: Print("making .....") Time.sleep (5) Q.put (count)Print('Producer%s has produced%s Baozi .'%(name, count)) Count+=1#Q.task_done ()Q.join ()Print("OK ...")defConsumer (name): Count=0 whileCount <10: Time.sleep (Random.randrange (4)) #if not Q.empty (): #print ("Waiting ...") #Q.join ()data =Q.get ()Print("eating ....") Time.sleep (4) Q.task_done ()#print (data) Print('\033[32;1mconsumer%s has eat%s baozi...\033[0m'%(name, data))#Else: #Print ("-----no Baozi anymore----")Count +=1P1= Threading. Thread (Target=producer, args= ('a June',)) C1= Threading. Thread (Target=consumer, args= ('B June',)) C2= Threading. Thread (Target=consumer, args= ('C-June',)) C3= Threading. Thread (Target=consumer, args= ('D-June',)) P1.start () C1.start () C2.start () C3.start ( )
python-Producer Consumer Model