Python 并发执行器对比与示例

1. ThreadPoolExecutor

作用:基于线程的并发执行器,适用于I/O密集型任务
特点:共享内存空间,受GIL限制,不能真正并行执行CPU密集型任务

1
2
3
4
5
6
7
8
9
10
11
12
from concurrent.futures import ThreadPoolExecutor
import time

def task(n):
time.sleep(1) # 模拟I/O操作
return n * 2

# 创建包含2个线程的线程池
with ThreadPoolExecutor(max_workers=2) as executor:
results = list(executor.map(task, [1, 2, 3]))

print("ThreadPoolExecutor结果:", results) # 输出: [2, 4, 6]

2. ProcessPoolExecutor

作用:基于进程的并发执行器,适用于CPU密集型任务
特点:独立内存空间,可利用多核CPU实现真正并行

1
2
3
4
5
6
7
8
9
10
11
from concurrent.futures import ProcessPoolExecutor
import math

def cpu_intensive_task(n):
return sum(math.sqrt(i) for i in range(n))

# 创建包含4个进程的进程池
with ProcessPoolExecutor(max_workers=4) as executor:
results = list(executor.map(cpu_intensive_task, [1000000]*4))

print("ProcessPoolExecutor结果:", [round(r, 2) for r in results])

3. AsyncPoolExecutor(以asyncio为例)

作用:异步任务执行器,适用于异步I/O操作
特点:单线程内实现并发,需配合async/await语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import asyncio
from concurrent.futures import ThreadPoolExecutor

async def async_task(n):
# 在异步中使用线程池执行阻塞任务
loop = asyncio.get_event_loop()
with ThreadPoolExecutor() as pool:
result = await loop.run_in_executor(pool, lambda: n*2)
return result

async def main():
tasks = [async_task(i) for i in [1,2,3]]
results = await asyncio.gather(*tasks)
print("Async结果:", results) # 输出: [2, 4, 6]

asyncio.run(main())

4. TaskExecutor(非标准库)

说明:Python标准库中无此组件,可能是:

  • 自定义任务调度器
  • 第三方框架组件(如Celery的TaskExecutor)
  • 某些框架中的抽象基类

通用实现示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from abc import ABC, abstractmethod

class TaskExecutor(ABC):
@abstractmethod
def execute(self, tasks):
pass

class SimpleTaskExecutor(TaskExecutor):
def execute(self, tasks):
return [task() for task in tasks]

# 使用示例
executor = SimpleTaskExecutor()
results = executor.execute([lambda: 1+1, lambda: 2+2])
print("自定义TaskExecutor结果:", results) # 输出: [2, 4]

核心差异对比

特性 ThreadPoolExecutor ProcessPoolExecutor AsyncPoolExecutor
并发模型 多线程 多进程 异步I/O
内存空间 共享 独立 共享
GIL限制 受影响 不受影响 单线程无影响
适用场景 I/O密集型 CPU密集型 异步I/O
数据通信效率 高(共享内存) 低(需IPC机制) 高(事件循环)