python-gevent模块(自动切换io的协程)

import gevent


def foo():

    print("Running in foo")
    gevent.sleep(2)
    print("Explicit context switch to foo again")


def bar():
    print("Explicit context to bar")
    gevent.sleep(1 )
    print("Implicit context switch back to bar")

def func3():
    print("running func3")
    gevent.sleep(0)#遇到io就切换,sleep最长2秒,所以整个程序花费两秒,如果是串行需要花费3秒
    print("running func3 again")

gevent.joinall([

    gevent.spawn(foo),#启动一个协程
    gevent.spawn(bar),
    gevent.spawn(func3)
]

)

 

posted @ 2018-06-26 18:30  努力乄小白  阅读(158)  评论(0编辑  收藏  举报