Producer consumer model and producer model
1 #! /Usr/bin/env python 2 # coding: UTF-8 3 from threading import Thread 4 from Queue import Queue 5 import time 6 7 8 9 10 class Procuder (Thread ): 11 def _ init _ (self, name, queue): 12 self. _ Name = name13 self. _ Queue = queue # Container 14 super (Procuder, self ). _ init _ () # execute the parent class constructor 15 def run (self): 16 while True: 17 if self. _ Queue. full (): 18 time. sleep (1) 19 else: 20 self. _ Queue. put ('item ') 21 time. sleep (1) 22 print '% s produced a commodity' % (self. _ Name,) 23 24 25 # Thread. run (self) 26 27 class Consumer (Thread): 28 29 def _ init _ (self, name, queue): 30 self. _ Name = name31 self. _ Queue = queue # container 32 super (Consumer, self ). _ init _ () # execute the parent class constructor 33 def run (self): 34 while True: 35 if self. _ Queue. empty (): 36 time. sleep (1) 37 else: 38 self. _ Queue. get () 39 time. sleep (1) 40 print '% s consumed a commodity' % (self. _ Name,) 41 que = Queue (maxsize = 100) 42 43 Dylan1 = Procuder ('dylan1', que) 44 Dylan1.start () 45 Dylan2 = Procuder ('dylan2 ', que) 46 Dylan2.start () 47 Dylan3 = Procuder ('dylan3', que) 48 Dylan3.start () 49 50 for item in range (20 ): 51 name = 'elasticity % d' % (item,) 52 elasticity = Consumer (name, que) 53 elasticity. start ()