浅谈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())
相关推荐
珠海西格电力2 分钟前
西格电力零碳园区管理系统的技术架构是怎样的?
大数据·运维·人工智能·物联网·架构·能源
MAHATMA玛哈特科技3 分钟前
矫平机的液压系统是干什么的?压下精度背后的控制逻辑
运维·服务器·校平机·矫平机·整平机
打码人的日常分享10 分钟前
信息化数据安全管理制度办法(Word)
大数据·运维·网络·云计算·制造
日取其半万世不竭23 分钟前
immich-low-memory-tuning-20260601
服务器·docker·容器
电商API_1800790524729 分钟前
技术分享:如何实现批量自动化获取淘宝商品视频主图API
运维·爬虫·数据挖掘·自动化
TG_yunshuguoji30 分钟前
亚马逊云代理商:如何用 CloudWatch+Lambda 打造自动化告警系统
大数据·运维·自动化·云计算·aws
maosheng114635 分钟前
网络综合项目(做个博客)
linux·服务器·网络
Irissgwe44 分钟前
6、传输层协议
linux·服务器·网络·传输层·udp协议
深圳市机智人激光雷达1 小时前
激光雷达:智慧港口自动化升级的核心感知基石
运维·人工智能·机器人·自动化·自动驾驶·无人机·激光雷达
酉鬼女又兒1 小时前
零基础入门计算机网络数据链路层:从基本概念、封装成帧到差错检测核心原理全解析
服务器·网络·网络协议·tcp/ip·计算机网络·考研·职场和发展