【10.1】python中的GIL

 1 #!/user/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 # gil global interpreter lock(cpython)全局解释器锁
 5 # python中一个线程对应于c语言中的一个线程
 6 # gil时的同一时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多个cpu上执行
 7 # gil会根据执行的字节码行数以及时间片释放gil,gil在遇到io操作时主动释放
 8 import threading
 9 total = 0
10 
11 
12 def add():
13     global total
14     for i in range(1000000):
15         total += 1
16 
17 
18 def desc():
19     global total
20     for i in range(1000000):
21         total -= 1
22 
23 
24 thread1 = threading.Thread(target=add)
25 thread2 = threading.Thread(target=desc)
26 
27 thread1.start()
28 thread2.start()
29 
30 thread1.join()
31 thread2.join()
32 
33 print(total)
C:\Users\Administrator\Python\imooc>python demo.py
-102343

C:\Users\Administrator\Python\imooc>python demo.py
-29159

C:\Users\Administrator\Python\imooc>python demo.py
-239340

猜你喜欢

转载自www.cnblogs.com/zydeboke/p/11294525.html