互斥锁和GIL解释器锁

什么是互斥锁

由于并发状态下,操作系统对多个进程进行调度,而多个进程可能都有操作硬件的需求,这时就会产生多个进程对资源的共享,而共享意味着竞争,会产生许多问题。这样就需要一种机制或者手段去解决竞争,使竞争变得有序化,从而使共享资源按照预定的结果去获取。这种手段就是加互斥锁

from threading import Thread,Lock
import time

n=100

def task():
    global n
    mutex.acquire()
    temp=n
    time.sleep(0.1)
    n=temp-1
    mutex.release()
    
if __name__ == '__main__':
    mutex=Lock()
    t_l=[]
    for i in range(100):
        t=Thread(target=task)
        t_l.append(t)
        t.start()

    for t in t_l:
        t.join()

    print('',n)

什么是GIL?

-GIL:全局解释器锁。每个线程在执行的过程都需要先获取GIL,保证同一时刻只有一个线程可以执行代码。仅仅是因为在CPython解释器,难以移除GIL。 
-当初操作系统还没有线程的概念,GIL锁对单线程来说带来了性能的提升。GIL是cpython开发者早期面对困难的一种解决方案。

线程释放GIL锁的情况

在IO操作等可能会引起阻塞的system call之前,可以暂时释放GIL,但在执行完毕后,必须重新获取GIL Python 3.x使用计时器(执行时间达到阈值后,当前线程释放GIL)或Python 2.x,tickets计数达到100

# 计算密集型:用多进程
from multiprocessing import Process
from threading import Thread
import os,time
def work():
    res=0
    for i in range(100000000):
        res*=i


if __name__ == '__main__':
    l=[]
    # print(os.cpu_count()) 
    start=time.time()
    for i in range(8):
        # p=Process(target=work) 
        p=Thread(target=work)
        l.append(p)
        p.start()
    for p in l:
        p.join()
    stop=time.time()
    print('run time is %s' %(stop-start))

第二种使用情况:

# IO密集型:用多线程
from multiprocessing import Process
from threading import Thread
import threading
import os,time

def work():
    time.sleep(2)

if __name__ == '__main__':
    l=[]
    # print(os.cpu_count()) 
    start=time.time()
    for i in range(400):
        # p=Process(target=work) 
        p=Thread(target=work)
        l.append(p)
        p.start()
    for p in l:
        p.join()
    stop=time.time()
    print('run time is %s' %(stop-start))

猜你喜欢

转载自www.cnblogs.com/z18271397173/p/9222054.html