python多线程的GIL锁

  • python线程的GIL问题(全局解释器锁)
来源:
python-->支持多线程-->同步互斥-->加锁-->超级锁,给解释器加锁-->解释器同一时刻只能解释一个线程

后果:一个解释器同一时刻只能解释执行一个线程,所以导致python线程效率低下。但是当遇到IO阻塞时线程会主动让出解释器,因此python线程更加适合高延迟的IO程序并发。

解决方法:
 * 尽量用进程完成并发
 * 不适用c解释器 
 * 尽量使用多种方案组合的方式进行并发操作,线程用作高延迟IO
  • 测试程序:
'''
测试任务:计算密集型程序与IO密集型程序
'''

#计算密集型
def count(x,y):
	c = 0
	while c < 6000000:
		c += 1
		x += 1
		y += 1

#IO密集函数
def write():
	f = open('test.txt','w')
	for i in range(1000000):
		f.write('hello world\n')
	f.close()

def read():
	f = open('test.txt','r')
	lines = f.readlines()
	f.close()

def io():
	write()
	read()
'''
单进程测试,两个程序各执行10次
'''

from test_func import *
import time

t = time.time()

#CPU密集型程序
#for i in range(10): 
#	count(1,1)  

#IO密集型程序
for i in range(10):
	write()
	read()    # 单线程1.9秒

print('Line cpu:',time.time() - t)
'''
多线程测试
'''

import threading
from test_func import *
import time

t = time.time()

threads = []

def main1():
	# 10个线程计算CPU密集型程序 
	for i in range(10):
		thread = threading.Thread(target = count,args = (1,1))
		threads.append(thread)
		thread.start()

	for thread in threads:
		thread.join()

def main():
	# 10个线程执行IO密集型程序
	for i in range(10):
		thread = threading.Thread(target = io)
		threads.append(thread)
		thread.start()

	for thread in threads:
		thread.join()


if __name__ == '__main__':
	main()
	print('time is',time.time() - t)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值