我正在研究并试图了解 python GIL 和在 python 中使用多线程的最佳实践。我找到了这个演示文稿和这个视频
我试图重现演示文稿前 4 张幻灯片中提到的奇怪和疯狂的问题。这个问题老师在视频中也提到过(前4分钟)。我写了这个简单的代码来重现问题
from threading import Thread
from time import time
BIG_NUMBER = 100000
count = BIG_NUMBER
def countdown(n):
global count
for i in range(n):
count -= 1
start = time()
countdown(count)
end = time()
print('Without Threading: Final count = {final_n}, Execution Time = {exec_time}'.format(final_n=count, exec_time=end - start))
count = BIG_NUMBER
a = Thread(target=countdown, args=(BIG_NUMBER//2,))
b = Thread(target=countdown, args=(BIG_NUMBER//2,))
start = time()
a.start()
b.start()
a.join()
b.join()
end = time()
print('With Threading: …
Run Code Online (Sandbox Code Playgroud)