掘金 人工智能 07月18日 10:53
Python3.14:终于摆脱了GIL的限制
index_new5.html
../../../zaker_core/zaker_tpl_static/wap/tpl_guoji1.html

 

Python 3.14 引入了可选的“Free-threaded”版本,移除了备受诟病的全局解释器锁(GIL)。本文通过 Mandelbrot 集合计算的基准测试,对比了 Python 3.10(GIL 启用)和 Python 3.14(GIL 禁用)在多线程环境下的性能表现。测试结果显示,在 Python 3.14 的无 GIL 版本中,多线程计算能够有效利用多核 CPU,显著缩短了计算时间,其表现已接近于多进程的并行计算效果。然而,文章也提醒,由于第三方库的兼容性问题,短期内不建议直接将此版本应用于生产环境,但其未来的发展潜力巨大。

✨ Python 3.14 引入了可选的“Free-threaded”版本,移除了 CPython 中长期存在的全局解释器锁(GIL)。GIL 的存在是为了保证线程安全,但牺牲了多线程在多核 CPU 上的并行性能,使得多线程在 CPU 密集型任务中无法充分发挥多核优势。

📊 通过使用 Mandelbrot 集合计算的基准测试,文章对比了 Python 3.10(GIL 启用)和 Python 3.14(GIL 禁用)在多线程环境下的性能。在 Python 3.10 版本中,多线程的性能提升非常有限,与单线程表现接近,验证了 GIL 的限制作用;而采用多进程则能有效利用多核。

🚀 在 Python 3.14 的“Free-threaded”版本中,测试结果显示,当线程数量增加时,Mandelbrot 计算的耗时显著缩短,与多进程的性能表现非常接近。这表明移除 GIL 后,Python 的多线程在 CPU 密集型任务中能够真正实现并行计算,大幅提升了性能。

⚠️ 尽管 Python 3.14 的无 GIL 版本在性能上展现出巨大潜力,但文章也指出,目前许多第三方库可能尚未完全适配这一新的设计。因此,作者建议在短期内谨慎使用,不建议直接应用于生产环境,但对其未来的发展持乐观态度,期待生态系统的逐步完善。

前言

Python中最遭人诟病的设计之一就是GIL。

GIL**(全局解释器锁)是 CPython 的一个互斥锁,确保任何时刻只有一个线程可以执行 Python 字节码,这样可以避免多个线程同时操作内部数据结构而引发竞争条件或内存错误。

简单来说,就是为了安全牺牲性能,在单核 CPU 时代无可厚非,但在多核 CPU 盛行的当下,已然过时。

Python 3.14 中,发布了两个版本,默认版本是包含GIL的版本,另一个可选“Free-threaded”版本包含了通过 PEP 703 引入的无 GIL 设计。

本文就来实测一下,在 python 3.14 中,取消 GIL 的版本是否有效。

实践测试

1. python 3.10 版本测试

首先测试一下 python 3.10,作为对照组的表现。

1.创建环境

uv venv --python 3.10

2.激活环境

.venv\Scripts\activate

3.编写并运行多线程测试脚本

让 Ai 编写了一个测试脚本,它选取了 Mandelbrot 集合进行模拟计算。

Mandelbrot 集合是一组复数集合点,这些点通过特定的迭代计算后不会发散。

import threading, time, sysdef mandelbrot_section(n, max_iter, y_start, y_end):    width = height = n    for py in range(y_start, y_end):        for px in range(width):            x0 = (px / width) * 3.5 - 2.5            y0 = (py / height) * 2.0 - 1.0            x = y = 0.0            iters = 0            while x*x + y*y <= 4.0 and iters < max_iter:                x, y = x*x - y*y + x0, 2*x*y + y0                iters += 1def run_benchmark(n=500, max_iter=200, thread_counts=[1, 2, 4]):    # print("GIL enabled?", sys._is_gil_enabled())    print(f"== mandelbrot({n}×{n}, iter={max_iter}) ==")    for num_threads in thread_counts:        threads = []        start = time.time()        rows_per_thread = n // num_threads        for i in range(num_threads):            y_start = i * rows_per_thread            y_end = n if i == num_threads - 1 else (i + 1) * rows_per_thread            th = threading.Thread(target=mandelbrot_section, args=(n, max_iter, y_start, y_end))            threads.append(th)            th.start()        for th in threads:            th.join()        total = time.time() - start        print(f"{num_threads} threads total: {total:.2f}s")    print()if __name__ == "__main__":    run_benchmark(n=500, max_iter=200, thread_counts=[1, 2, 4])

多线程输出结果。

== mandelbrot(500×500, iter=200) ==1 threads total: 1.84s2 threads total: 1.83s4 threads total: 1.82s

采用多个线程运算,效果几乎不变,说明 GIL 生效。

在此版本中,为了发挥多核并行计算优势,只能采用多进程的方式。

import multiprocessingimport timedef mandelbrot_section(n, max_iter, y_start, y_end):    width = height = n    for py in range(y_start, y_end):        for px in range(width):            x0 = (px / width) * 3.5 - 2.5            y0 = (py / height) * 2.0 - 1.0            x = y = 0.0            iters = 0            while x * x + y * y <= 4.0 and iters < max_iter:                x, y = x * x - y * y + x0, 2 * x * y + y0                iters += 1def run_benchmark(n=500, max_iter=200, proc_counts=[124]):    print(f"== mandelbrot({n}×{n}, iter={max_iter}) ==")    for num_procs in proc_counts:        procs = []        start = time.time()        rows_per_proc = n // num_procs        for i in range(num_procs):            y_start = i * rows_per_proc            y_end = n if i == num_procs - 1 else (i + 1) * rows_per_proc            p = multiprocessing.Process(target=mandelbrot_section, args=(n, max_iter, y_start, y_end))            procs.append(p)            p.start()        for p in procs:            p.join()        total = time.time() - start        print(f"{num_procs} processes total: {total:.2f}s")    print()if __name__ == "__main__":    multiprocessing.freeze_support()  # for Windows support    run_benchmark(n=500, max_iter=200, proc_counts=[124])

结果如下。

== mandelbrot(500×500, iter=200) ==1 processes total: 1.60s2 processes total: 0.91s4 processes total: 0.81s

2. python 3.14 特定版本测试

1.创建环境

uv venv --python 3.14+freethreaded

2.激活环境

.venv\Scripts\activate

3.运行 GIL 检查脚本

import sysprint(sys._is_gil_enabled()) 

输出 False,说明 GIL 关闭成功。

4.运行多线程脚本

运行和上面一致的多线程测试脚本,输出结果如下:

== mandelbrot(500×500, iter=200) ==1 threads total: 1.69s2 threads total: 0.94s4 threads total: 0.72s

由此可以看出,多线程加速处理能够成功生效。

总结

虽然 python 3.14(freethreaded)移除了 GIL 这个历史包袱,但很多第三方依赖仍然需要进行适配,短期不建议直接应用于生产环境,期待后续发展。

Fish AI Reader

Fish AI Reader

AI辅助创作,多种专业模板,深度分析,高质量内容生成。从观点提取到深度思考,FishAI为您提供全方位的创作支持。新版本引入自定义参数,让您的创作更加个性化和精准。

FishAI

FishAI

鱼阅,AI 时代的下一个智能信息助手,助你摆脱信息焦虑

联系邮箱 441953276@qq.com

相关标签

Python GIL 多线程 性能优化 Free-threaded
相关文章