【发布时间】:2017-06-29 08:15:02
【问题描述】:
看这段代码:
from threading import Thread
import time
cpt = 0
def myfunction():
print("myfunction.start")
global cpt
for x in range(10):
cpt += 1
time.sleep(0.2)
print("cpt=%d" % (cpt))
print("myfunction.end")
thread1 = Thread(target=myfunction)
thread2 = Thread(target=myfunction)
thread1.start()
thread2.start()
这是一个读取/写入全局变量的非常基本的函数。 我在同一个函数上运行 2 个线程。
我读到 python 在多线程方面效率不是很高,因为 GIL 会自动锁定访问相同资源的函数或方法。 所以,我在想python会先运行thread1,然后是thread2,但我可以在控制台输出中看到2个线程是并行运行的。 所以我不明白gil真正锁定的是什么......
谢谢
【问题讨论】:
-
GIL 与“访问相同的资源”无关。
-
GIL 锁定在 Python 字节码级别,而不是函数或方法。
标签: python multithreading gil