递归锁,死锁

互相等待另外一个线程的释放

 1 import threading
 2 import time
 3 
 4 
 5 class MyThread(threading.Thread):
 6     def action(self):
 7         lock1.acquire()
 8         time.sleep(1)
 9         print(self.name,'got A',time.time())
10         lock2.acquire()
11         print(self.name,'got B',time.time())
12         lock2.release()
13         lock1.release()
14     def actonB(self):
15         lock2.acquire()
16         time.sleep(1)
17         print(self.name,'got B',time.time())
18         lock1.acquire()
19         print(self.name,'got A',time.time())
20         lock1.release()
21         lock2.release()
22     def run(self):
23         self.action()
24         self.actonB()
25 
26 l = list()
27 lock1 = threading.Lock()
28 lock2 = threading.Lock()
29 for i in range(5):
30     t=MyThread()
31     l.append(t)
32     t.start()
33 for i in l:
34     i.join()
35 print('ending.....')
36 输出:
37 Thread-1 got A 1586753664.8394556
38 Thread-1 got B 1586753664.8394556
39 Thread-2 got A 1586753665.8402793
40 Thread-1 got B 1586753665.8402793

结论:一把锁只能是有一次。      有的锁还没有解开,其它的线程就开始执行了。导致死锁的产生。

解决办法:使用一把锁。Rlock

 1 import threading
 2 import time
 3 
 4 
 5 class MyThread(threading.Thread):
 6     def action(self):
 7         r_lock.acquire()
 8         time.sleep(1)
 9         print(self.name,'got A',time.time())
10         r_lock.acquire()
11         print(self.name,'got B',time.time())
12         r_lock.release()
13         r_lock.release()
14     def actonB(self):
15         r_lock.acquire()
16         time.sleep(1)
17         print(self.name,'got B',time.time())
18         r_lock.acquire()
19         print(self.name,'got A',time.time())
20         r_lock.release()
21         r_lock.release()
22     def run(self):
23         self.action()
24         self.actonB()
25 
26 l = list()
27 # lock1 = threading.Lock()
28 # lock2 = threading.Lock()
29 r_lock = threading.RLock()
30 for i in range(5):
31     t=MyThread()
32     l.append(t)
33     t.start()
34 for i in l:
35     i.join()
36 print('ending.....')
37 输出:
38 Thread-1 got A 1586754305.5835774
39 Thread-1 got B 1586754305.5835774
40 Thread-1 got B 1586754306.5840476
41 Thread-1 got A 1586754306.5840476
42 Thread-3 got A 1586754307.5844278
43 Thread-3 got B 1586754307.5844278
44 Thread-3 got B 1586754308.5852091
45 Thread-3 got A 1586754308.5852091
46 Thread-5 got A 1586754309.5857675
47 Thread-5 got B 1586754309.5857675
48 Thread-5 got B 1586754310.585957
49 Thread-5 got A 1586754310.585957
50 Thread-4 got A 1586754311.586401
51 Thread-4 got B 1586754311.586401
52 Thread-4 got B 1586754312.5868573
53 Thread-4 got A 1586754312.5868573
54 Thread-2 got A 1586754313.587585
55 Thread-2 got B 1586754313.587585
56 Thread-2 got B 1586754314.5880973
57 Thread-2 got A 1586754314.5880973
58 ending.....

原理:内部有一个计数器,只要有所存在就不会被其他的线程使用cpu。

勇士一把锁可以无限次的使用。  开了多少把锁就必须等到所有的锁都接触以后才能运行其它的线程。

猜你喜欢

转载自www.cnblogs.com/ch2020/p/12690746.html
今日推荐