σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft Academy学习路线
Ctrl K
AO
+1.2k 位学习者
登录加入 ↗
学习路线
AO
+1.2k 位学习者
登录
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
Python 学习路线›模块 10 · 高性能 Python 工程›主题 10.9·~55分钟高级

线程与 GIL

路线进度模块 10/11 · 主题 9/13
10.9 线程与 GIL
—实验得分— / 100总 XP—连续天数—

线程:单个进程内的并发

线程是单个程序内部的独立执行线索,与其他线程共享内存。一个需要从十个交易场所取行情、写日志并保持界面响应的交易程序会使用线程,这样等待其中一个就不会让其余的停下。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 s

GIL:等待的线程与计算的线程

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 cores
线程常常比你想象的更不合适线程适合 I/O:大量缓慢而相互独立的等待。要在单个进程里处理很多连接,(本路线图前面讲过的)asyncio 通常扩展性更好,而且在 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 分
资源管理器 · lab-125-1
▾ lab-125-1
…
bash · 浏览器内
learner@quantcraft:~/lab-125-1$
Python 尚未加载PythonLn 1, Col 1Spaces: 4UTF-8

要重置此主题吗?

lab-125-1 中的所有内容将恢复为初始文件,终端也会被清空。你当前的解答将丢失,且无法撤销。

将被重置
  • main.py → 初始代码
  • 终端历史与测试输出
  • 未提交的更改
将被保留
  • 实验最高得分
  • 你的 XP 与连续天数
  • 讲解进度与笔记

登录后即可运行你的代码。

所有讲解均可免费阅读。创建账户或登录后,即可运行代码、运行测试并提交此实验。

  • 浏览器内 IDE 与 bash 终端,无需安装
  • 即时评分、XP 以及你在学习路线中的位置
创建账户登录
或
使用 GitHub 继续