python thread模块使用心得(包括lock锁)

#coding=utf8
import thread
from time import sleep,ctime

def loop0():
	print "loop0 start at:",ctime()
	sleep(4)
	print "loop0 end at",ctime()
	
def loop1(lock):#多线程传入锁对象
	print "loop1start at:",ctime()
	sleep(4)
	print "loop1 end at",ctime()
	lock.release()#循环结束后释放锁

def main():
	lock1 = thread.allocate_lock()#分配一个lockType的锁对象
	lock1.acquire()获取锁对象
	thread.start_new_thread(loop0,())
	thread.start_new_thread(loop1,(lock1,))
	while(lock1.locked()):#等待锁释放后跳出循环
		print "lock!"
		sleep(1)
	sleep(6)
	print "all down at",ctime()
	
if __name__=="__main__":
	main()

>>> 
loop0 start at: Mon Nov 03 13:07:08 2014
loop1start at: Mon Nov 03 13:07:08 2014
lock!
lock!
lock!
lock!
loop1 end at Mon Nov 03 13:07:12 2014
loop0 end at Mon Nov 03 13:07:12 2014
all down at Mon Nov 03 13:07:18 2014

备注:不提倡使用thread模块,因为thread模块会因为主线程提前退出导致分配的子线程提前结束。

 
  

你可能感兴趣的:(个人成长)