浅谈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())
相关推荐
还不秃顶的计科生1 分钟前
“please restart word to load mathtype“解决方法
运维·服务器
傻啦嘿哟6 分钟前
Python文件目录比较全攻略:从基础到实战
服务器·前端·数据库
YANshangqian9 分钟前
微软Microsoft Edge浏览器 v143.0.3650.75 基于Chromium内核
linux·运维·服务器
机智的爆爆哥17 分钟前
使用 `glab` 管理多个内网 GitLab 实例:配置详解与合并请求自动化
运维·自动化·gitlab
wanhengidc22 分钟前
服务器的安全保障如何
运维·服务器·安全·web安全·php
2501_9419820523 分钟前
群成员标签与属性的 RPA 维护与用户画像自动化
运维·自动化·rpa
xjxijd24 分钟前
AWS Proton 2.0 实测:一键生成 CI/CD 流水线,云原生部署效率提 200%
服务器·aws
亚控科技25 分钟前
亚控信创SCADA以全栈国产化方案,筑牢航空燃油安全供应生命线
运维·人工智能·安全·kingscada·亚控科技
无奈笑天下9 小时前
银河麒麟高级服务器操作系统【双网卡绑定之bond0】操作方法
linux·运维·服务器·网络·经验分享
无名3879 小时前
FusionPBX Debian 12 安装
运维·debian·通信