4. Using Python Builder to implement a simple "producer consumer" model

Source: Internet
Author: User

If there is no such object as a generator, how can this simple "producer-consumer" model be implemented?

Import time

Def producer ():

Pro_list = []

For I in range (10000):

Print "Bun%s made ing"% (i)

Time.sleep (0.5)

Pro_list.append ("Bun%s"%i)

Return pro_list

DEF consumer (pro_list):

For Index,stuffed_bun in Enumerate (pro_list):

Print "%s personal, ate the first%s buns"% (Index,stuffed_bun)

Pro_list = producer ()

Consumer (pro_list)


Above this producer and consumer model has a serious problem, is the very low efficiency, and in the "production" process, the consumer to wait, has been waiting for all the buns are finished production, consumers can eat, this model inefficient and unreasonable.


To improve efficiency, it is necessary to modify the production process, production and consumption process should be two independent individuals, production and consumption should be "concurrent" (simultaneous) operation.


Import time

DEF consumer (name):

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

While True:

Stuffed_bun = yield

Time.sleep (1)

Print "%s ate%s very happily"% (Name,stuffed_bun)

Def producer ():

P1 = Consumer ("Suhaozhi")

P2 = consumer ("Ayumi")

P1.next () # After executing the next method, the dead loop begins

P2.next ()

For I in range (10):

Time.sleep (1)

P1.send ("Bun%s"% (i)) # is assigned to yield by send, and yield is assigned a value to Stuffed_bun

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

Producer ()


This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1908969

4. Using Python Builder to implement a simple "producer consumer" model

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.