python 协程

2019-08-29  本文已影响0人  足__迹

什么是协程

协程和线程的差异

协程底层原理(举例)
'''
1,协程的实现原理,底层通过 yield 实现
'''

def work1(): #工作任务
    for i in range(10):
        print('work1----{}'.format(i))
        yield i

def work2():
    for i in range(10):
        print('work2----{}'.format(i))
        yield i

def work3():
    for i in range(10):
        print('work3----{}'.format(i))
        yield i


g1 = work1()
g2 = work2()
g3 = work3()

while True: #循环调用生成器实现任务切换
    try:
        print(next(g1))
        print(next(g2))
        print(next(g3))
    except StopIteration :
        pass
        break

协程 greenlet

python -m pip install greenlet
示例

'''
1,展示greenelent ,不能自动切换需要手动切换
'''
import greenlet

def work1():
    for i in range(10):
          print('work1----{}'.format(i))
          g2.switch()    #切换到g2



def work2():
    for i in range(10):
          print('work2----{}'.format(i))
          g1.switch()  #切换到g1



g1 = greenlet.greenlet(work1)  #返回协程对象
g2 = greenlet.greenlet(work2)

g1.switch()  #启动开关

执行顺序

gevent

'''
协程gevent IO操作会切换
'''
import gevent


def work1():  # 工作任务
    for i in range(10):
        print('work1----{}'.format(i))
        gevent.sleep(0.5)


def work2():
    for i in range(10):
        print('work2----{}'.format(i))
        gevent.sleep(0.5)


g1 = gevent.spawn(work1) #指定工作函数
g2 = gevent.spawn(work2) #指定工作函数
g1.join()    #等待协程执行完成再往下走
g2.join()


上一篇下一篇

猜你喜欢

热点阅读