有没有办法证明“一次只能有一个线程执行代码”?
一个奇怪的发现是,我看到多个内核在htop
中运行,好像有多个线程同时在执行,那是什么?
(我想这样做的原因是,我正在使用pybind
将cpp代码绑定到python,并且正在处理一些GIL释放策略,所以我想看看有多少线程正在执行)
答案 0 :(得分:1)
尝试运行一些使用大量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