threading模块,python下的多线程

一、GIL全局解释器锁

In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)

无论你启动多少个线程,Python解释器在同一时刻,都只允许一个线程在cpu上执行,Python启动一个线程是调用C语言的接口,让操作系统启动线程,所以所有的线程调度是操作系统在执行,而Python解释器在启动线程后只能等待操作系统返回结果。所以Python解释器为了防止同一时刻多个线程操作同一个数据,造成数据混乱,所以在cpython解释器中,加入了global interpreter lock。

注意:Jpython、pypy等解释器都没有GIL

二、Python中的多线程
  • python 中的多线程虽然不能并行,但是能达到高并发的效果。并不是一无用处
2.1 threading模块
import threading
import time
 
def run(i): #定义每个线程要运行的函数
 
    print("线程::%s  正在运行" %i)
 
    time.sleep(1)
 
if __name__ == '__main__':
 
    t1 = threading.Thread(target= run, args=(1,)) #生成一个线程实例     参数还有name 线程名,daemon 是否守护线程 True
    t2 = threading.Thread(target= run, args=(2, )) #生成另一个线程实例
 
    t1.start() #启动线程
    t2.start() #启动另一个线程
 
    print(t1.getName()) #获取线程名
    print(t2.getName())
2.2 Join及守护线程

当你在启动一个线程之后,前面说过由于是调用系统创建,所以主进程就和创建的线程没有关系了,

猜你喜欢

转载自www.cnblogs.com/shiqi17/p/9545391.html