A detailed explanation of Python's two modes of producer consumer model

  • 2021-01-02 21:55:23
  • OfStack

The first is implemented using queue queues:


# Producer consumer model   In fact, the server cluster is this model 
#  Here's the right and wrong yield Method implementation process 

import threading,time
import queue
q = queue.Queue(maxsize=10)

def Producer(anme):
 # for i in range(10):
 #  q.put(' The bone %s'%i)
 count = 1
 while True:
  q.put(' The bone %s'%count)
  print(' Produced bone ',count)
  count += 1
  time.sleep(1)

def Consumer(name):
 # while q.qsize() >0:
 while True:
  print('[%s]  Get to the [%s]  And ate it ...'%(name,q.get()))
  time.sleep(1)

p = threading.Thread(target=Producer,args=('shenchanzhe',))
c = threading.Thread(target=Consumer,args=('xiaofeizhe01',))
c1 = threading.Thread(target=Consumer,args=('xiaofeizhe02',))

p.start()
c.start()
c1.start()

The yield coroutines are used to implement producers and consumers:


# The way producers and consumers use generators is that 1 A simple parallel, 
import time
#  This is a 1 A consumer  1 Waiting for the complete action of eating the steamed stuffed bun 
def consumer(name):
 print('%s Ready to eat baozi! '%name) # Print out the name of the corresponding consumer 
 while True: # perform 1 An infinite loop   In fact, it will only be executed when it needs to be called, and will stop at no call yield
  baozi = yield # When it receives the content, it passes it on baozi
  print(' The steamed stuffed bun" %s Coming, being [ %s 】 ate '%(baozi,name))
def producer(name):
 c1 = consumer('A') # It's just the c1 become 1 A generator 
 c2 = consumer('B')
 c1.__next__() # The first 1 a next It just gets there yield Then stop 
 c2.__next__()
 print(' I started making baozi ')
 for i in range(1,10):
  time.sleep(1)
  print('3 S made two buns ')
  c1.send(i) # this 1 A step is really just a call next The method is passed simultaneously 1 A parameter i to field Receive, and then baozi=i
  c2.send(i+1)
  # It actually looks something like this send "Just keep going yield The following statement, and then go yield Stop here again 

# producer('aea')
c = consumer('aaa') # no next1 This will execute the program 1 time 
c.__next__()
c.__next__()
c.__next__()

Related articles: