Home  >  Article  >  Backend Development  >  Introduction to the method of implementing the producer-consumer model using python generators

Introduction to the method of implementing the producer-consumer model using python generators

高洛峰
高洛峰Original
2017-03-22 09:38:081448browse

If there is no such object as a generator, how to implement this simple "producer-consumer" model?

import time

def producer():

pro_list = []

for i in range(10000):

print "Baozi %s making" %(i)

time.sleep(0.5)

pro_list.append("Baozi %s" %i)

return pro_list

def consumer(pro_list):

for index, stuffed_bun in enumerate(pro_list):

print "The %s person ate the %s bun" %( index, stuffed_bun)

pro_list = producer()

consumer(pro_list)

The above producer and consumer model has a serious problem, which is extremely low efficiency , and during the "production" process, consumers have to wait until all the buns are produced before consumers can eat them. This model is inefficient and unreasonable.

If you want to improve efficiency, you must modify the production process. The production and consumption processes should be two independent individuals, and production and consumption should operate "concurrently" (simultaneously).

import time

def consumer(name):

print 'I am %s, ready to start eating steamed buns'%(name)

while True:

      stuffed_bun = yield

      time.sleep(1)

                                      ’ s ’s to eat %s’ %’s to %s---- %(name, stuffed_bun)

def producer():

p1 = consumer("suhaozhi")

p2 = consumer("ayumi")

p1.next() # After executing the next method, the infinite loop begins

p2.next()

for i in range(10):

time.sleep(1)

p1.send("Bun %s" %(i)) #Assign a value to yield through send, and yield will assign the value to stuffed_bun

p2.send("Bun %s" %(i))

producer()

The above is the detailed content of Introduction to the method of implementing the producer-consumer model using python generators. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn