对python多线程中Lock()与RLock()锁详解
资源总是有限的,程序运行如果对同一个对象进行操作,则有可能造成资源的争用,甚至导致死锁
也可能导致读写混乱
锁提供如下方法:
1.Lock.acquire([blocking])
2.Lock.release()
3.threading.Lock()加载线程的锁对象,是一个基本的锁对象,一次只能一个锁定,其余锁请求,需等待锁释放后才能获取
4.threading.RLock()多重锁,在同一线程中可用被多次acquire。如果使用RLock,那么acquire和release必须成对出现,
调用了n次acquire锁请求,则必须调用n次的release才能在线程中释放锁对象
例如:
无锁:
#coding=utf8 importthreading importtime num=0 defsum_num(i): globalnum time.sleep(1) num+=i printnum print'%sthreadstart!'%(time.ctime()) try: foriinrange(6): t=threading.Thread(target=sum_num,args=(i,)) t.start() exceptKeyboardInterrupt,e: print"youstopthethreading" print'%sthreadend!'%(time.ctime())
输出:
SunMay2820:54:592017threadstart! SunMay2820:54:592017threadend! 01 3 710 15
结果显示混乱
引入锁:
#coding=utf8 importthreading importtime num=0 defsum_num(i): lock.acquire() globalnum time.sleep(1) num+=i printnum lock.release() print'%sthreadstart!'%(time.ctime()) try: lock=threading.Lock() list=[] foriinrange(6): t=threading.Thread(target=sum_num,args=(i,)) list.append(t) t.start() forthreadinglistinlist: threadinglist.join() exceptKeyboardInterrupt,e: print"youstopthethreading" print'%sthreadend!'%(time.ctime())
结果:
SunMay2821:15:372017threadstart! 0 1 3 6 10 15 SunMay2821:15:432017threadend!
其中:
lock=threading.Lock()加载锁的方法也可以换成lock=threading.RLock()
如果将上面的sum_num修改为:
lock.acquire() globalnum lock.acquire() time.sleep(1) num+=i lock.release() printnum lock.release()
那么:
lock=threading.Lock()加载的锁,则一直处于等待中,锁等待
而lock=threading.RLock()运行正常
以上这篇对python多线程中Lock()与RLock()锁详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。