浅谈Python之并发任务

一、基本介绍

在 Python 中实现方法的并发执行,通常涉及到多线程、多进程或者异步编程(协程)。

二、并发编程示例

使用 asyncio 模块进行协程并发 : Python 的 asyncio 模块是实现异步 I/O 操作的标准库,它允许你以异步的方式编写并发代码。使用 async def 定义异步函数,然后在事件循环中使用 await 来调用这些函数。你可以使用 asyncio.gather 来并发运行多个协程。

python 复制代码
import asyncio

async def task(name, delay):
    print(f"Task {name} started")
    await asyncio.sleep(delay)
    print(f"Task {name} finished")

async def main():
    task1 = task('A', 1)
    task2 = task('B', 2)
    await asyncio.gather(task1, task2)

asyncio.run(main())

使用线程池 : concurrent.futures.ThreadPoolExecutor 提供了一个线程池实现,可以用来并发执行多个线程任务。

python 复制代码
from concurrent.futures import ThreadPoolExecutor
import time

def task(name):
    print(f"Task {name} started")
    time.sleep(1)
    print(f"Task {name} finished")

with ThreadPoolExecutor(max_workers=5) as executor:
    executor.map(task, ['A', 'B', 'C', 'D', 'E'])

使用进程池 : concurrent.futures.ProcessPoolExecutor 类似于线程池,但是它使用多个进程来执行任务,这在 CPU 密集型任务中特别有用。

python 复制代码
from concurrent.futures import ProcessPoolExecutor

def cpu_intensive_task(name):
    print(f"Task {name} started")
    # 模拟 CPU 密集型任务
    return [x * x for x in range(10000)]

with ProcessPoolExecutor(max_workers=4) as executor:
    results = executor.map(cpu_intensive_task, ['A', 'B', 'C', 'D'])

使用 asyncio 与 aiohttp 进行并发 HTTP 请求 : aiohttp 是一个支持异步请求的 HTTP 客户端/服务端框架,可以与 asyncio 结合使用来并发地发送 HTTP 请求。

python 复制代码
import aiohttp
import asyncio

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, f'http://example.com/{i}') for i in range(10)]
        responses = await asyncio.gather(*tasks)
        for response in responses:
            print(response)

asyncio.run(main())

使用 asyncio 的并发控制机制 : asyncio 提供了多种并发控制机制,如 Semaphore、Event、Lock 等,可以用来控制协程的并发执行。

python 复制代码
import asyncio

async def limited_task(semaphore):
    async with semaphore:
        print("Task is running")
        await asyncio.sleep(1)
        print("Task finished")

async def main():
    semaphore = asyncio.Semaphore(2)
    tasks = [limited_task(semaphore) for _ in range(5)]
    await asyncio.gather(*tasks)

asyncio.run(main())
相关推荐
yyuuuzz1 小时前
跨境电商云服务器,五个店铺挤一台机器
运维·服务器·人工智能·云服务器
鲁邦通物联网1 小时前
AMR到站未出梯的机器人梯控故障归属分析与分段诊断方法
运维·网络·机器人·机器人梯控·agv梯控·非侵入式采集·机器人乘梯
CoderYanger1 小时前
Java EE 进阶:15. Linux基本使用和程序部署(第二弹):部署 Web 项目到 Linux
linux·服务器·数据库·spring boot·spring·阿里云·java-ee
1024+1 小时前
Ubuntu 系统设置虚拟内存
linux·运维·ubuntu
加搜科技观察1 小时前
自动化仓库应该如何选择 WMS 系统?
运维·自动化
天远Date Lab2 小时前
零信任架构实战:基于天远运营商近3个月欠费次数构建自动化通信履约评估网关
运维·人工智能·架构·自动化
飞花漫卷,情随岁迁2 小时前
Linux 排障与性能监控
linux·运维·服务器·网络·数据库·mysql·oracle
ESDWAN2 小时前
AI Agent兴起:从智能问答到企业工作流自动化
运维·人工智能·自动化
fengkai45452 小时前
Python对接LangChain智能体开发(Tool工具调用与 Agent智能体)
运维·开发语言·python·langchain·llm·ai agent·tool
福大大架构师每日一题2 小时前
agno v3.2.1发布:会话压缩、公司文件 API、工具稳定性与模型兼容性全面升级
服务器·网络·数据库