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