python多线程——thread模块

介绍

闲来无事整理下python关于多线程相关的知识点,对于thread模块只是用于介绍多线程,真正开发时建议使用更高级别的threading模块。

代码

import _thread as thread
from time import sleep,ctime

loops = [4,2]

def loop(nloop,nsec,lock):
	print('start loop ',nloop,' at:',ctime())
	sleep(nsec)
	print('loop ',nloop,' done at:',ctime())
	lock.release()
	
def main():
	print('starting at:',ctime())
	locks = []
	nloops = range(len(loops))
	
	for i in nloops:
		lock = thread.allocate_lock()# 分配锁对象
		lock.acquire()	# 尝试获取锁对象(把锁锁上)
		locks.append(lock)# 添加到锁列表中

	for i in nloops:# 派生线程
	# 调用loop()函数,传递循环号,睡眠时间以及用于该线程的锁
		thread.start_new_thread(loop,(i,loops[i],locks[i]))
	# 思考:为啥不在上锁的循环中启动线程
	
	
	for i in nloops:# 直到所有锁都被释放之后才会继续执行
		while locks[i].locked():pass
		
	print('all DONE at:',ctime())

if __name__ == "__main__":
	main()

结果

starting at: Tue Sep  8 15:17:04 2020
start loop  1  at: Tue Sep  8 15:17:04 2020
start loop  0  at: Tue Sep  8 15:17:04 2020
loop  1  done at: Tue Sep  8 15:17:06 2020
loop  0  done at: Tue Sep  8 15:17:08 2020
all DONE at: Tue Sep  8 15:17:08 2020

猜你喜欢

转载自blog.csdn.net/XZ2585458279/article/details/108469404