一.python中的GIL(Global Interpreter Lock)
详情:https://www.cnblogs.com/SuKiWX/p/8804974.html
介绍:
GIL:全局解释器锁(Cpython中才有,Jpython没有,pypy是去gil的);
cpython:pyhon中的一个线程对应C语言中的一个线程;
gil使得同一个时刻只有一个线程在一个cpu上执行字节码,无法将多个线程映射到多cpu上;
gil在一些情况下会释放,是结合字节码和时间片释放(Python2和Python3有差别),gil在遇到io操作的时候会主动释放
#gil会释放,最后的结果不定 import threading total=1 def add(): global total for i in range(1000000): total+=1 def decs(): global total for i in range(1000000): total-=1 thread1=threading.Thread(target=add) thread2=threading.Thread(target=decs) thread1.start() thread2.start() thread1.join() thread2.join() print(total)
注:
Python GIL其实是功能和性能之间权衡后的产物,它尤其存在的合理性,也有较难改变的客观因素。从本分的分析中,我们可以做以下一些简单的总结:
-
-
-
- 因为GIL的存在,只有IO Bound场景下得多线程会得到较好的性能
- 如果对并行计算性能较高的程序可以考虑把核心部分也成C模块,或者索性用其他语言实现
- GIL在较长一段时间内将会继续存在,但是会不断对其进行改进
-
-