浅谈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'])

使用 asyncioaiohttp 进行并发 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 提供了多种并发控制机制,如 SemaphoreEventLock 等,可以用来控制协程的并发执行。

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())
相关推荐
土星云SaturnCloud3 小时前
边缘侧大模型部署的新利器——国科环宇GK 300I大模型一体机深度评测与架构解析
服务器·人工智能·ai·边缘计算
晚风吹长发4 小时前
Docker基础——Docker Network(网络详解)
linux·运维·网络·ubuntu·docker·容器
Cx330_FCQ4 小时前
Tmux使用
服务器·git·算法
高磊20055 小时前
LVS(Linux virual server)
linux·服务器·lvs
LedgerNinja5 小时前
WEEX API 自动化交易实践:下单、撤单、订单查询与状态闭环
运维·自动化
山峰哥6 小时前
数据库性能救星:Explain执行计划深度拆解
服务器·开发语言·数据库·sql·启发式算法
执笔画流年呀6 小时前
Linux搭建Java项目部署环境
java·linux·运维
Dory_Youth7 小时前
联想笔记本电脑失灵
运维·笔记·电脑
W.W.H.7 小时前
嵌入式 Linux外接USB/WIFI模块兼容5G频段实战
linux·运维·5g·wifi
运维大师7 小时前
【K8S 运维实战】24-资源优化HPA与VPA
运维·kubernetes·github