1. 什么是GIL全局解释器锁
GIL本质就是一把互斥锁,相当于执行权限,每个进程内都会存在一把GIL,同一进程内的多个线程 必须抢到GIL之后才能使用Cpython解释器来执行自己的代码,即同一进程下的多个线程无法实现并行 但是可以实现并发
在Cpython解释器下,如果想实现并行可以开启多个进程
2. 为何要有GIL
因为Cpython解释器的垃圾回收机制不是线程安全的
3. 如何用GIL
有了GIL,应该如何处理并发
# from threading import Thread
# import time
#
# def task(name):
# print('%s is running' %name)
# time.sleep(2)
#
# if __name__ == '__main__':
# t1=Thread(target=task,args=('线程1',))
# t2=Thread(target=task,args=('线程1',))
# t3=Thread(target=task,args=('线程1',))
# t1.start()
# t2.start()
# t3.start()
计算密集型:应该使用多进程
# 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(6): # # 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)) #4.271663427352905
IO密集型: 应该开启多线程
from multiprocessing import Process from threading import Thread import threading import os,time def work(): time.sleep(2) if __name__ == '__main__': l=[] start=time.time() for i in range(300): # p=Process(target=work) #2.225289821624756 p=Thread(target=work) #2.002105951309204 l.append(p) p.start() for p in l: p.join() stop=time.time() print('run time is %s' %(stop-start))