一段代碼程序員
def CountDown(n): while n > 0: n -= 1 # CountDown(100000000) #==8秒 from threading import Thread n = 100000000 t1 = Thread(target=CountDown, args=[n // 2]) t2 = Thread(target=CountDown, args=[n // 2]) t1.start() t2.start() t1.join() t2.join() #==9s
GIL,是最流行的 Python 解釋器 CPython 中的一個技術術語。它的意思是全局解釋器鎖,本質上是相似操做系統的 Mutex。每個 Python 線程,在 CPython 解釋器中執行時,都會先鎖住本身的線程,阻止別的線程執行。CPython 會作一些小把戲,輪流執行 Python 線程。安全
for (;;) { if (--ticker < 0) { ticker = check_interval; /* Give another thread a chance */ PyThread_release_lock(interpreter_lock); /* Other threads may run now */ PyThread_acquire_lock(interpreter_lock, 1); } bytecode = *next_instr++; switch (bytecode) { /* execute the next instruction ... */ } }
GIL 的設計,主要是爲了方便 CPython 解釋器層面的編寫者,而不是 Python 應用層面的程序員。多線程
做爲 Python 的使用者,咱們仍是須要 lock 等工具,來確保線程安全。好比下面的這個例子:工具
n = 0 lock = threading.Lock() def foo(): global n with lock: n += 1
事實上,不少高性能應用場景都已經有大量的 C 實現的 Python 庫,例如 NumPy 的矩陣運算,就都是經過 C 來實現的,並不受 GIL 影響。 因此,大部分應用狀況下,你並不須要過多考慮 GIL。由於若是多線程計算成爲性能瓶頸,每每已經有 Python 庫來解決這個問題了。性能
極客時間《Python核心技術實戰》專欄ui