Python异步编程之 协程 & asyncio & 异步

时间:2022-07-24
本文章向大家介绍Python异步编程之 协程 & asyncio & 异步,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

协程

实现协程的方法:

  1. greenlet 早期模块
  2. yield关键字
  3. asyncio装饰器(python3.4加入)
  4. async、await关键字(python3.5加入)推荐使用

asyncio的使用

在python3.4及之后加入内置模块

import asyncio


@asyncio.coroutine
def func1():
    print('函数func1')
    yield asyncio.sleep(5)
    print('函数func1完成')


@asyncio.coroutine
def func2():
    print('函数func2')
    yield asyncio.sleep(3)
    print('函数func2完成')


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

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

async & await 关键字

python3.5之后版本

import asyncio


async def func1():
    print('函数func1')
    await asyncio.sleep(5)
    print('函数func1完成')


async def func2():
    print('函数func2')
    await asyncio.sleep(3)
    print('函数func2完成')


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

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))