【协程】协程概念

1、协程

  • 协程不是计算机提供的,是由程序员人为的创建的
  • 协程(Coroutine):也可以被称为微线程,是一种用户态内的上下文切换技术。简而言之,其实就是通过一个线程实现代码块相互切换执行

2、实现协程的几种方法

  • greenlet
  • yield关键字
  • asyncio装饰器(py3.4)
  • async await关键字(py3.5)【推荐】

3、greenlet实现协程

pip3 install greenlet
from greenlet import greenlet


def func1():
    print(1)  # 第二步,输出1
    gr2.switch()
    print(2)  # 第四步,输出2
    gr2.switch() # 第六步,无输出


def func2():
    print(3) # 第三步,输出3
    gr1.switch()
    print(4) # 第五步,输出4 

gr1 = greenlet(func1)
gr2 = greenlet(func2)

gr1.switch() # 执行第一步

4、asyncio装饰器实现协程

# -*- coding: utf-8 -*-
import asyncio


@asyncio.coroutine
def func1():
    print(1)
    yield from asyncio.sleep(2) # 通过IO耗时操作,自动化切换到tasks中的其他任务
    print(3)


@asyncio.coroutine
def func2():
    print(2)
    yield from asyncio.sleep(2) # 通过IO耗时操作,自动化切换到tasks中的其他任务
    print(4)


tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2())
]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
  • 注意:遇到IO阻塞自动切换

5、async&await关键字【py3.5以后】

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2) # 通过IO耗时操作,自动化切换到tasks中的其他任务
    print(3)


async def func2():
    print(2)
    await asyncio.sleep(2) # 通过IO耗时操作,自动化切换到tasks中的其他任务
    print(4)


tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2())
]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
  • 注意:遇到IO阻塞自动切换

posted @ 2022-05-31 14:01  郭祺迦  阅读(89)  评论(0)    收藏  举报