python避免死锁方法实例分析
本文实例讲述了python避免死锁方法。分享给大家供大家参考。具体分析如下:
当两个或者更多的线程在等待资源的时候就会产生死锁,两个线程相互等待。
在本文实例中thread1等待thread2释放block,thread2等待thtead1释放ablock,
避免死锁的原则:
1.一定要以一个固定的顺序来取得锁,这个列子中,意味着首先要取得alock,然后再去block
2.一定要按照与取得锁相反的顺序释放锁,这里,应该先释放block,然后是alock
importthreading,time a=5 alock=threading.Lock() b=5 block=threading.Lock() defthread1calc(): print"thread1acquiringlocka" alock.acquire() time.sleep(5) print"thread1acquiringlockb" block.acquire() a+=5 b+=5 print"thread1releasingbothlocks" block.release() alock.release() defthread2calc(): print"thread2acquiringlockb" block.acquire() time.sleep(5) print"thread2acquiringlocka" alock.acquire() time.sleep(5) a+=10 b+=10 print"thread2releasingbothlocks" block.release() alock.release() t=threading.Thread(target=thread1calc) t.setDaemon(1) t.start() t=threading.Thread(target=thread2calc) t.setDaemon(2) t.start() while1: time.sleep(300)
输出:
thread1acquiringlocka thread2acquiringlockb thread1acquiringlockb thread2acquiringlocka
希望本文所述对大家的Python程序设计有所帮助。