Python中GIL

GIL(global interpreter lock)全局解释器锁

python中GIL使得同一个时刻只有一个线程在一个cpu上执行,无法将多个线程映射到多个cpu上执行,但GIL并不会一直占有,它会在适当的时候释放

 1 import threading
 2 
 3 
 4 count = 0
 5 
 6 
 7 def add():
 8     global count
 9     for i in range(10**6):
10         count += 1
11 
12 
13 def minus():
14     global count
15     for i in range(10**6):
16         count -= 1
17 
18 
19 thread1 = threading.Thread(target=add)
20 thread2 = threading.Thread(target=minus)
21 thread1.start()
22 thread2.start()
23 thread1.join()
24 thread2.join()
25 print(count)

分别运行三次的结果:

-59452
60868
-77007

可以看到count并不是一个固定值,说明GIL会在某个时刻释放,那么GIL具体在什么情况下释放呢:

1.执行的字节码行数到达一定阈值

2.通过时间片划分,到达一定时间阈值

3.在遇到IO操作时,主动释放

猜你喜欢

转载自www.cnblogs.com/FG123/p/9703952.html