import threading
# Python 的全局解释器锁(GIL)是 CPython 解释器的一个机制,
# 它确保在任何时刻只有一个线程在执行 Python 字节码。
# 这意味着即使在多核 CPU 上,Python 线程也无法真正并行运行。
# 下面是一个简单的例子来演示 GIL 的影响:
def count(num):
while num > 0:
num -= 1
# 创建两个线程,分别执行 count 函数
thread1 = threading.Thread(target=count, args=(10**8,))
thread2 = threading.Thread(target=count, args=(10**8,))
# 记录开始时间
start_time = time.time()
# 启动线程
thread1.start()
thread2.start()
# 等待线程结束
thread1.join()
thread2.join()
# 记录结束时间
end_time = time.time()
print(f"Time taken: {end_time - start_time} seconds")
# 你会发现,尽管有两个线程在运行,但它们并没有显著加快程序的执行速度,
# 这是因为 GIL 的存在使得这两个线程不能同时执行 Python 字节码。
上一篇:python env
下一篇:python获取当前日期
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站