线程:单个进程内的并发
线程是单个程序内部的独立执行线索,与其他线程共享内存。一个需要从十个交易场所取行情、写日志并保持界面响应的交易程序会使用线程,这样等待其中一个就不会让其余的停下。Python 的 threading 模块,以及更方便的 concurrent.futures.ThreadPoolExecutor,负责启动和管理线程。由于线程共享变量,它们通信很快,但出错也很危险。
# Ten slow "network calls" in a thread pool wait at the same time, so the total is about one call, not ten
import time
from concurrent.futures import ThreadPoolExecutor
def fetch_quote(symbol):
time.sleep(0.1) # stands in for waiting on a venue
return symbol, len(symbol) * 10.0
symbols = ["AAPL", "MSFT", "NVDA", "TSLA", "AMZN", "META", "GOOG", "NFLX", "ORCL", "INTC"]
start = time.perf_counter()
with ThreadPoolExecutor(max_workers=10) as pool:
quotes = list(pool.map(fetch_quote, symbols))
elapsed = time.perf_counter() - start
print(quotes[0], len(quotes)) # ('AAPL', 40.0) 10
print(elapsed < 0.5) # True about 0.1 s in total, not 10 x 0.1 sGIL:等待的线程与计算的线程
CPython 有全局解释器锁(GIL):任一时刻只有一个线程在执行 Python 字节码。线程在等待网络、文件或 time.sleep 时会让出它,所以线程能很好地重叠等待:十个取行情的线程大约在一个线程的时间内完成。但对于 CPU 密集的 Python 代码(做算术的纯 Python 循环),线程只是轮流执行,所以四个线程并不比一个快,往往还略慢。运行在 Python 之外的代码,比如 NumPy 或会释放 GIL 的 C 扩展,可以在线程中并行运行。对繁重的纯 Python 计算,使用独立进程(下一节),或在可用时使用 Python 3.13+ 去掉 GIL 的 free-threaded 版本。
# Splitting a list into chunks for workers: sizes differ by at most one, the first chunks get the extra items
def split_chunks(items, workers):
size, extra = divmod(len(items), workers)
chunks, start = [], 0
for index in range(workers):
stop = start + size + (1 if index < extra else 0)
chunks.append(list(items[start:stop]))
start = stop
return chunks
chunks = split_chunks(list(range(7)), 3)
print(chunks) # [[0, 1, 2], [3, 4], [5, 6]]
print([sum(chunk) for chunk in chunks]) # [3, 7, 11] one partial sum per worker
print(sum(sum(chunk) for chunk in chunks)) # 21共享数据、竞态条件与锁
多个线程更新同一个变量可能会把它搞坏,因为 total += amount 是三步(读、加、写),线程切换可能发生在它们之间:两个线程都读到 100,都加 5,都写入 105,于是丢了一次更新。这就是竞态条件,它很少出现且不可预测,因此是最糟糕的一类 bug。解决办法是锁:with lock: 让一次只有一个线程执行这段代码,读和写都必须在其中。更好的办法是避免共享:给每个工作者自己的数据块和自己的结果,最后再合并结果,或通过本来就线程安全的 queue.Queue 传递工作和结果。
# A lock makes the read-modify-write a single step; the total comes out exact
import threading
totals = {"AAPL": 0}
lock = threading.Lock()
def safe_add(shared, key, amount, lock):
with lock:
shared[key] = shared.get(key, 0) + amount
return shared[key]
def worker():
for _ in range(10_000):
safe_add(totals, "AAPL", 1, lock)
threads = [threading.Thread(target=worker) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(totals["AAPL"]) # 40000 nothing lost: four threads x 10,000 additions# A back-of-envelope estimate before writing any threaded code
import math
def estimate_time(n_tasks, seconds, workers, kind):
if kind in ("io", "processes"):
return math.ceil(n_tasks / workers) * seconds
return n_tasks * seconds # "cpu_threads": the GIL makes the threads take turns
print(estimate_time(40, 0.5, 8, "io")) # 2.5 forty slow requests, eight at a time
print(estimate_time(40, 0.5, 8, "cpu_threads")) # 20.0 forty CPU-bound tasks in threads: no gain
print(estimate_time(40, 0.5, 8, "processes")) # 2.5 separate processes use separate coresasyncio 通常扩展性更好,而且在 await 之间没有竞态。数组上的算术用 NumPy 向量化,CPU 密集的 Python 用进程。如果确实要在线程间共享数据,就要让加锁的部分尽量短,持锁时永远不要调用慢的代码,并且在所有地方以相同顺序获取多个锁,否则两个线程可能永远互相等待(死锁)。- 线程共享内存,能很好地重叠等待(网络、文件);一个
ThreadPoolExecutor可以同时向多个场所取数。 - GIL 让一次只有一个线程运行 Python 字节码:CPU 密集的纯 Python 不会提速,但 NumPy 和 C 扩展可以释放它。
- 用
with lock:包住读和写来保护共享更新,尽量不共享(数据块、队列),并留意死锁。
下一节:多进程(multiprocessing),用多个进程让每个 CPU 核心都投入工作。
实验:评分内容
- 用
split_chunks分配工作25 分 - 用
run_in_chunks对各块应用函数25 分 - 用
safe_add保护共享数据25 分 - 用
estimate_time了解线程能带来什么25 分