import time def foo(): print("******start*****") print("this is the first line") r1 = yield 'r1' print("this is the second value:%s" % r1) r2 = yield 'r2' print("this is the third value:%s" % r2) r3 = yield 'r3' print("this is the last value:%s" % r3) f = foo() f.send(None) var1 = f.send('send 1') #传回给上一个yield的值 print(var1) #r2返回来的还是yield后边的值 #https://www.cnblogs.com/zhangxinqi/p/8337207.html #方法一:yield实现协程 def consumer(): r = '' while True: var = yield r if not var: return print("[Consumer] is consume: %s"%var) time.sleep(3) r = "200 OK" def produce(c): next(c) n = 0 while n < 5: n = n+1 print("[Produce] is produce: %s" % n) r = c.send(n) print("[Produce] consumer return: %s "%r) c.close() if __name__ == "__main__": c = consumer() produce(c) #方法二:gevent实现协程 #gevent会主动识别程序内部的IO操作,当子程序遇到IO后,切换到别的子程序。如果所有的子程序都进入IO,则阻塞。 import gevent def foo(): print("foo is running") gevent.sleep(2) print("from Bar to Foo running ") def bar(): print("bar is running") gevent.sleep(2) print("from Foo to Bar running ") gevent.joinall([gevent.spawn(foo), gevent.spawn(bar)]) #创建线程并行执行程序,碰到IO就切换
生成器中的send
最新推荐文章于 2021-08-15 10:19:07 发布