python中避免死锁的方法介绍

python scott 111℃ 0评论

在python中经常会导致死锁发生,那么如何才能很好的避免死锁的发生呢?下面将会介绍几个python中避免死锁的方法:

本文实例讲述了python避免死锁方法。分享给大家供大家参考。具体分析如下:

当两个或者更多的线程在等待资源的时候就会产生死锁,两个线程相互等待。

在本文实例中 thread1 等待thread2释放block , thread2等待thtead1释放ablock,

避免死锁的原则:

1. 一定要以一个固定的顺序来取得锁,这个列子中,意味着首先要取得alock, 然后再去block

2. 一定要按照与取得锁相反的顺序释放锁,这里,应该先释放block,然后是alock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import threading ,time
a = 5
alock = threading.Lock()
b = 5
block = threading.Lock()
def thread1calc():
  print "thread1 acquiring lock a"
  alock.acquire()
  time.sleep(5)
  print "thread1 acquiring lock b"
  block.acquire()
  a+=5
  b+=5
  print "thread1 releasing both locks"
  block.release()
  alock.release()
def thread2calc():
  print "thread2 acquiring lock b"
  block.acquire()
  time.sleep(5)
  print "thread2 acquiring lock a"
  alock.acquire()
  time.sleep(5)
  a+=10
  b+=10
  print "thread2 releasing both locks"
  block.release()
  alock.release()
t = threading.Thread(target = thread1calc)
t.setDaemon(1)
t.start()
t = threading.Thread(target = thread2calc)
t.setDaemon(2)
t.start()
while 1:
  time.sleep(300)

输出:

1
2
3
4
thread1 acquiring lock a
thread2 acquiring lock b
thread1 acquiring lock b
thread2 acquiring lock a

python中避免死锁的方法介绍就是这样,欢迎大家参考。。。。

转载请注明:osetc.com » python中避免死锁的方法介绍

喜欢 (0)or分享 (0)
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址