1.协程
1 import gevent 2 3 4 def foo(): 5 print('Running in foo') 6 gevent.sleep(0) 7 print('Explicit context switch to foo again') 8 9 10 def bar(): 11 print('Explicit context to bar') 12 gevent.sleep(0) 13 print('Implicit context switch back to bar') 14 ''' 15 遇到sleep就切换到下一个 16 ''' 17 18 gevent.joinall([ 19 gevent.spawn(foo), 20 gevent.spawn(bar), 21 ])
结果显示:如注释所写,遇到sleep就切换。
Running in foo Explicit context to bar Explicit context switch to foo again Implicit context switch back to bar
2.协程原理
1 def consumer(name): 2 print("--->starting eating baozi...") 3 while True: 4 new_baozi = yield 5 print("[%s] is eating baozi %s" % (name, new_baozi)) 6 # time.sleep(1) 7 8 9 def producer(): 10 r = con.__next__() 11 r = con2.__next__() 12 n = 0 13 while n < 5: 14 n += 1 15 con.send(n) 16 con2.send(n) 17 print("