import threading
# 全局解释器锁 GIL
# python 一个线程对应于c语言中的一个线程
import dis
# def add(a):
# a = a+1
# return a
# 反编译
# print(dis.dis(add))
# GIL根据执行的字节码行数、时间片,GIL在遇到IO操作主动释放
# GIL释放例子
total = 0
def add():
global total
for i in range(10000000):
total +=1 # 线程不安全
def desc():
global total
for i in range(10000000):
total -=1
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print(total)
# 167499
# 1518478
本文探讨了Python中线程的实现原理,重点讲解了全局解释器锁(GIL)的作用及其对线程并发执行的影响。通过示例代码演示了GIL在遇到IO操作时的释放机制,并通过一个简单的线程不安全的计数增减实验,展示了GIL如何限制多线程程序的实际性能。
965

被折叠的 条评论
为什么被折叠?



