1 #author F2 3 #parallel effect on single thread (generator)4 #co-process5 6 Import Time7 defConsumer (name):8 Print("%s prepare to eat steamed buns."%name)9 whileTrue:TenBaozi =yield One Print("steamed bun%s has been eaten by%s!"%(Baozi, name)) A -c = Consumer ("WW")#The consumer is not a function at this point. He's a generator. It just initializes a generator. - #c.send ("[Beef meat]") theC.__next__()#you have to execute a Next statement before you get to yield. -C.send ("[Pork meat]")#send syntax to pass the parameter to the generator - - defproducer (name): +c = Consumer ("A") -C2 = Consumer ("B") +C.__next__() AC2.__next__() at Print("Lao Tzu began to prepare buns!") - forIinchRange (1, 11): -Time.sleep (1) - Print("made a stuffed bun! Two people share food") - c.send (i) - c2.send (i) in -Producer"F")
Python Generator: Single Cheng