Python协程并发优化:从串行执行到asyncio.gather

林舟
林舟
发布时间:2026-10-14| 4人浏览过
原创

本文深入解析Python协程中的任务添加与并发执行机制。通过对比串行调用asyncio.run与使用asyncio.gather创建子任务的代码示例,揭示串行执行导致的时间浪费问题。重点演示如何利用asyncio.gather在await期间实现任务间调度,从而将总耗时从串行累加降低至最长子任务耗时,充分发挥并发编程优势。

Python协程任务添加基础

1、添加一个任务


task2 = visit_url('http://another.com', 3)
asynicio.run(task2)

2、上述两个程序串行执行,总共消耗约 5s 的时间。这种写法并未发挥并发编程的优势。

串行执行的性能瓶颈分析


import asyncio
import time
async def visit_url(url, response_time):
  """访问 url"""
  await asyncio.sleep(response_time)
  return f"访问{url}, 已得到返回结果"

async def run_task():
  """收集子任务"""
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asyncio.run(task)
  await asyncio.run(task_2)
asyncio.run(run_task())
print(f"消耗时间:{time.perf_counter() - start_time}")

3、若采用正确的并发编程方式,该程序仅需消耗 3s,即等于耗时最长的 task2 的等待时间。

要实现并发编程效果,需对前述代码进行调整。使用 asyncio.gather 可创建 2 个子任务,当遇到 await 语句时,程序将在这些子任务之间进行调度切换。

利用asyncio.gather实现并发调度


async def run_task():
  """收集子任务"""
  task = visit_url('http://wangzhen.com', 2)
  task_2 = visit_url('http://another', 3)
  await asynicio.gather(task1, task2)

实例扩展:

跨线程协程执行扩展实例


import asyncio
from threading import Thread
 
 
async def production_task():
  i = 0
  while True:
    # 将consumption这个协程每秒注册一个到运行在线程中的循环,thread_loop每秒会获得一个一直打印i的无限循环任务
    asyncio.run_coroutine_threadsafe(consumption(i),
                     thread_loop) # 注意:run_coroutine_threadsafe 这个方法只能用在运行在线程中的循环事件使用
    await asyncio.sleep(1) # 必须加await
    i += 1
 
 
async def consumption(i):
  while True:
    print("我是第{}任务".format(i))
    await asyncio.sleep(1)
 
 
def start_loop(loop):
  # 运行事件循环, loop以参数的形式传递进来运行
  asyncio.set_event_loop(loop)
  loop.run_forever()
 
 
thread_loop = asyncio.new_event_loop() # 获取一个事件循环
run_loop_thread = Thread(target=start_loop, args=(thread_loop,)) # 将次事件循环运行在一个线程中,防止阻塞当前主线程
run_loop_thread.start() # 运行线程,同时协程事件循环也会运行
 
advocate_loop = asyncio.get_event_loop() # 将生产任务的协程注册到这个循环中
advocate_loop.run_until_complete(production_task()) # 运行次循环

到此这篇关于python在协程中增加任务实例操作的文章就介绍到这了,更多相关python在协程中增加任务内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。