赞
踩
目录
2.3.3、使用asyncio.wait()函数多任务异步执行
2.3.4、使用asyncio.gather()函数多任务异步执行
1、python提供了asyncio模块来支持异步编程,其中涉及到coroutines、event loops、task、futures四个核心概念;
2、异步编程框架的整个执行过程:
- import asyncio
-
- # 定义协程函数
- async def my_coroutine(delay, name):
- # 协程的具体实现
- print(f"{name} start my_coroutine")
- await asyncio.sleep(delay)
- print(f"{name} end my_coroutine")
-
- # 定义协程函数
- async def main():
- # 等待my_coroutine(1, 'hello')执行完成
- await my_coroutine(1, 'hello')
- # 等待my_coroutine(2, 'world')执行完成
- await my_coroutine(2, 'world')
-
- # 创建事件循环对象
- loop = asyncio.get_event_loop()
- # 添加任务到事件循环中
- loop.run_until_complete(main())
-
- # 等价于上面两行代码,推荐使用
- # asyncio.run(main())

说明:创建task任务将my_coroutine函数添加到task中,把上面的代码改成多任务异步执行过程,所谓的多任务异步执行就是:
asyncio.create_task(coro, *, name=None, context=None)
- # 定义协程函数
- async def main():
- # 创建task1
- task1 = asyncio.create_task(
- my_coroutine(1, 'hello'))
- # 创建task2
- task2 = asyncio.create_task(
- my_coroutine(2, 'world'))
-
- # TODO: 将task1和task2添加到事件循环中执行
- import asyncio
- async def my_coroutine(delay, name):
- # 协程的具体实现
- print(f"{name} start my_coroutine")
- await asyncio.sleep(delay)
- print(f"{name} end my_coroutine")
-
- # 定义协程函数
- async def main():
- task1 = asyncio.create_task(
- my_coroutine(1, 'hello'))
-
- task2 = asyncio.create_task(
- my_coroutine(2, 'world'))
- # 异步执行task1、task2
- await task1
- await task2
-
- asyncio.run(main())
-
- # 执行结果
- """
- hello start my_coroutine
- world start my_coroutine
- hello end my_coroutine
- world end my_coroutine
- """

coroutine asyncio.wait(aws, *, timeout=None, return_when=ALL_COMPLETED)
done, pending = await asyncio.wait(aws)
- async def my_coroutine(delay, name):
- # 协程的具体实现
- print(f"{name} start my_coroutine")
- await asyncio.sleep(delay)
- print(f"{name} end my_coroutine")
-
- # 定义协程函数
- async def main():
- task1 = asyncio.create_task(
- my_coroutine(1, 'hello'))
-
- task2 = asyncio.create_task(
- my_coroutine(2, 'world'))
-
- task = [task1, task2]
- await asyncio.wait(task)
-
- asyncio.run(main())
-
- # 执行结果
- """
- hello start my_coroutine
- world start my_coroutine
- hello end my_coroutine
- world end my_coroutine
- """

awaitable asyncio.gather(*aws, return_exceptions=False)
完整代码实现如下:
- async def my_coroutine(delay, name):
- # 协程的具体实现
- print(f"{name} start my_coroutine")
- await asyncio.sleep(delay)
- print(f"{name} end my_coroutine")
-
- # 定义协程函数
- async def main():
- results = await asyncio.gather(my_coroutine(1, 'hello'), my_coroutine(2, 'world'))
- print(results)
-
- asyncio.run(main())
-
-
- # 执行结果
- """
- hello start my_coroutine
- world start my_coroutine
- hello end my_coroutine
- world end my_coroutine
- """

awaitable loop.run_in_executor(executor, func, *args)
示例代码如下:
- import time
- from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
-
- def task(name, delay):
- n = 3
- while n:
- print(f"{name}: {n}")
- time.sleep(delay)
- n -= 1
-
- async def main():
- loop = asyncio.get_running_loop()
-
- # 使用loop默认的执行器执行(使用的是线程池)
- fs = [loop.run_in_executor(None, task, *args) for args in [("A", 3), ("B", 2), ("C", 1)]]
- await asyncio.wait(fs)
-
- # # 使用线程池执行非异步任务task
- # with ThreadPoolExecutor(max_workers=3) as pool:
- # fs = [loop.run_in_executor(pool, task, *args) for args in [("A", 3), ("B", 2), ("C", 1)]]
- # await asyncio.wait(fs)
- #
- # # 使用进程池执行非异步任务task
- # with ProcessPoolExecutor(max_workers=1) as pool:
- # fs = [loop.run_in_executor(pool, task, *args) for args in [("A", 3), ("B", 2), ("C", 1)]]
- # await asyncio.wait(fs)
-
-
- if __name__ == '__main__':
- asyncio.run(main())
-
- # 执行结果
- """
- A: 3
- B: 3
- C: 3
- C: 2
- B: 2
- C: 1
- A: 2
- B: 1
- A: 1
- """"

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。