Python3-gevent模块-单线程下的"并发"-协程

博客转载

  http://www.cnblogs.com/alex3714/articles/5248247.html

  http://www.cnblogs.com/tkqasn/p/5705338.html

代码示例

import greenlet


def func1():
    print(1)
    gr2.switch()
    print(1)
    gr2.switch()


def func2():
    print(2)
    gr3.switch()
    print(2)
    gr3.switch()


def func3():
    print(3)
    gr1.switch()
    print(3)
    gr1.switch()

# greenlet可以实现函数间的任意中断切换执行
gr1 = greenlet.greenlet(func1)
gr2 = greenlet.greenlet(func2)
gr3 = greenlet.greenlet(func3)
gr1.switch()
greenlet

import gevent


def func1():
    print(1)
    gevent.sleep()
    print(1)


def func2():
    print(2)
    gevent.sleep(1)
    print(2)


def func3():
    print(3)
    gevent.sleep()
    print(3)


# gevent封装了greenlet,可以通过sleep()交出控制权,实现协程
gevent.joinall([
    gevent.spawn(func1),
    gevent.spawn(func2),
    gevent.spawn(func3)
])
gevent

 

你可能感兴趣的:(Python3-gevent模块-单线程下的"并发"-协程)