黒猿の家:pythonジェネレータのyieldによる単一スレッドでの同時演算の効果...

833 ワード

単一スレッドの場合の同時演算の効果codeをyieldで実現
# Author:     

import time
def consumer(name):
    print("%s       !" %name)
    while True:
       baozi = yield

       print("  [%s]  , [%s]  !" %(baozi,name))

# c = consumer("ChenRonghua")
# c.__next__()
#__next__      yield , send     yield,    yield   
# b1= "   "
# c.send(b1)
# c.__next__()

def producer():
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("          !")
    for i in range(10):
        time.sleep(1)
        print("  1   ,   !")
        c.send(i)
        c2.send(i)

producer()
#            
#         ,         
#    ,             
#      io   
#                ,       
#              ,       
#   1   ,   !
#   [9]  , [A]  !
#   [9]  , [B]  !