首页 › Python 进阶 › 并发编程:线程、进程与 asyncio

并发编程:线程、进程与 asyncio

当程序需要同时处理多件事情(例如同时下载多个文件),就需要并发编程。Python 提供了三种主要方式:多线程、多进程和异步 IO。

先分清两类任务

CPython 有全局解释器锁(GIL),同一时刻只有一个线程执行 Python 字节码,所以多线程无法让纯计算任务变快,但等待 IO 时会释放 GIL,因此对 IO 密集型任务很有效。

线程池

concurrent.futures 提供了简单统一的接口:

import time
from concurrent.futures import ThreadPoolExecutor

def download(name):
    time.sleep(1)               # 模拟网络等待
    return f"{name} 下载完成"

files = [f"file{i}.zip" for i in range(5)]

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
    for result in pool.map(download, files):
        print(result)
print(f"耗时 {time.perf_counter() - start:.1f} 秒")   # 约 1 秒,而不是 5 秒

进程池

把 ThreadPoolExecutor 换成 ProcessPoolExecutor,每个任务会在独立的进程中运行,可以利用多个 CPU 核心:

from concurrent.futures import ProcessPoolExecutor

def count_primes(limit):
    count = 0
    for n in range(2, limit):
        if all(n % d for d in range(2, int(n ** 0.5) + 1)):
            count += 1
    return count

if __name__ == "__main__":
    with ProcessPoolExecutor() as pool:
        print(list(pool.map(count_primes, [50_000, 60_000, 70_000])))

使用多进程时,启动代码必须放在 if __name__ == "__main__": 中,否则在 Windows 上会反复创建子进程。

线程安全

多个线程同时修改同一个数据时,需要加锁:

import threading

counter = 0
lock = threading.Lock()

def add():
    global counter
    for _ in range(100_000):
        with lock:
            counter += 1

threads = [threading.Thread(target=add) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(counter)    # 400000

asyncio

asyncio 用单线程实现并发,通过 async/await 在等待 IO 时切换到其他任务,适合同时处理成百上千个网络连接:

import asyncio

async def fetch(name, delay):
    await asyncio.sleep(delay)          # 模拟网络请求
    return f"{name} 完成({delay}s)"

async def main():
    results = await asyncio.gather(
        fetch("任务A", 1),
        fetch("任务B", 2),
        fetch("任务C", 1.5),
    )
    for r in results:
        print(r)

asyncio.run(main())    # 总耗时约 2 秒

怎么选

场景推荐
少量并发的网络请求、文件操作ThreadPoolExecutor
大量并发连接(爬虫、聊天服务)asyncio + aiohttp/httpx
计算密集型任务ProcessPoolExecutor
并发会让程序变复杂、难以调试。先确认性能瓶颈确实在等待或计算上,再引入并发。

练习题

学完本节后,试着独立完成下面的练习,再展开参考答案对照。

练习 1 用线程池并发执行 5 个各需要 0.5 秒的模拟任务,验证总耗时约为 0.5 秒。

查看参考答案
import time
from concurrent.futures import ThreadPoolExecutor

def task(i):
    time.sleep(0.5)
    return i * i

start = time.perf_counter()
with ThreadPoolExecutor(max_workers=5) as pool:
    print(list(pool.map(task, range(5))))
print("耗时少于 1 秒:", time.perf_counter() - start < 1)
参考输出:
[0, 1, 4, 9, 16]
耗时少于 1 秒: True

练习 2 用 asyncio 并发运行 3 个协程,并按完成的先后顺序输出结果。

查看参考答案
import asyncio

async def job(name, delay):
    await asyncio.sleep(delay)
    return name

async def main():
    tasks = [job("A", 0.3), job("B", 0.1), job("C", 0.2)]
    for coro in asyncio.as_completed(tasks):
        print(await coro)

asyncio.run(main())
参考输出:
B
C
A