一段代码程序员
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