greenlet手動gevent自動切換協程
阿新 • • 發佈:2019-01-11
greenlet手動切換協程
from greenlet import greenlet
def tes_1():
print(12)
gr2.switch()#協程手動切換
print(34)
gr2.switch()#協程切換
def tes_2():
print(56)
gr1.switch()#協程切換
print(78 )
gr1 = greenlet(tes_1) #生成兩個協程
gr2 = greenlet(tes_2)
gr1.switch()#協程切換
gevent自動切換協程
import gevent
def foo():
print("running in foo")
gevent.sleep(2) #IO阻塞2秒 自動切換下一個協程
print('Explict context switch to foo again')
def bar():
print("Explicit精確的 context上下文切換 to bar")
gevent.sleep(1)#IO阻塞1秒
print('Implicit context switch back to bar')
def func3():
print("running func3")
gevent.sleep(0)#IO不阻塞,釋放 就先執行下面程式碼
print("running func3 again" )
gevent.joinall([
gevent.spawn(foo),#生成協程
gevent.spawn(bar),
gevent.spawn(func3),
])