如何演示 python GIL(我怎么知道一次只有一个线程在执行)
how to demonstrate python GIL (how do I know there is only one thread executing at a time)
有什么方法可以演示吗'only one thread can is executing code at a time'?
一个奇怪的观察是我在htop
中看到多个核心运行,好像有多个线程在同时执行,那是什么?
(我之所以要这样做,是因为我正在使用 pybind
将我的 cpp 代码绑定到 python,并且我正在处理一些 GIL 发布策略,所以我想看看有多少线程正在执行)
尝试 运行 一些使用大量 CPU 的难题,例如计算斐波那契数列的第 15800000 项。使用 IDLE 在单个线程上大约需要 2 秒。现在尝试做两个。
import threading
import timeit
def tesr():
a, b = 1, 0
for _ in range(15800000):
a, b = a + b, b
# Current thread
print("Current thread time:")
print(timeit.timeit(
stmt='tesr()',
setup='from __main__ import tesr',
number=1,
))
print()
# Single thread
print("Single thread time:")
print("(Should take about the same time as current)")
t = threading.Thread(target=tesr)
print(timeit.timeit(
stmt='t.start(); t.join()',
setup='from __main__ import t',
number=1,
))
print()
# Two threads
t1, t2 = (threading.Thread(target=tesr) for _ in range(2))
print("Two threads time:")
print("(Should take about double the current / single time)")
print(timeit.timeit(
stmt='t1.start(); t2.start(); t1.join(); t2.join()',
setup='from __main__ import t1, t2',
number=1,
))
我的输出:
Current thread time:
2.0613602900000387
Single thread time:
(Should take about the same time as current)
2.228870080999968
Two threads time:
(Should take about double the current / single time)
4.671865998000044
有什么方法可以演示吗'only one thread can is executing code at a time'?
一个奇怪的观察是我在htop
中看到多个核心运行,好像有多个线程在同时执行,那是什么?
(我之所以要这样做,是因为我正在使用 pybind
将我的 cpp 代码绑定到 python,并且我正在处理一些 GIL 发布策略,所以我想看看有多少线程正在执行)
尝试 运行 一些使用大量 CPU 的难题,例如计算斐波那契数列的第 15800000 项。使用 IDLE 在单个线程上大约需要 2 秒。现在尝试做两个。
import threading
import timeit
def tesr():
a, b = 1, 0
for _ in range(15800000):
a, b = a + b, b
# Current thread
print("Current thread time:")
print(timeit.timeit(
stmt='tesr()',
setup='from __main__ import tesr',
number=1,
))
print()
# Single thread
print("Single thread time:")
print("(Should take about the same time as current)")
t = threading.Thread(target=tesr)
print(timeit.timeit(
stmt='t.start(); t.join()',
setup='from __main__ import t',
number=1,
))
print()
# Two threads
t1, t2 = (threading.Thread(target=tesr) for _ in range(2))
print("Two threads time:")
print("(Should take about double the current / single time)")
print(timeit.timeit(
stmt='t1.start(); t2.start(); t1.join(); t2.join()',
setup='from __main__ import t1, t2',
number=1,
))
我的输出:
Current thread time:
2.0613602900000387
Single thread time:
(Should take about the same time as current)
2.228870080999968
Two threads time:
(Should take about double the current / single time)
4.671865998000044