-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeadlock.py
More file actions
63 lines (54 loc) · 1.35 KB
/
deadlock.py
File metadata and controls
63 lines (54 loc) · 1.35 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""
Notes:
* Interleave the locks
* Need the while True to ensure the deadlock happens
* You can add a countA and countB if it's hard to tell that the deadlock has happened
Sources:
* https://medium.com/swlh/getting-started-with-concurrency-in-python-part-ii-deadlocks-the-producer-consumer-model-gil-ae28afec3e7e
Output:
A acquired lock1
A acquired lock2
AAA
A released lock1
A released lock2
A acquired lock1
A acquired lock2
AAA
A released lock1
A released lock2
B acquired lock2
A acquired lock1
[Stalls here with B waiting A to release lock1 and A waiting for B to release lock2]
"""
import threading
def fnA(lock1, lock2):
while True:
lock1.acquire()
print("A acquired lock1")
lock2.acquire()
print("A acquired lock2")
print("AAA")
lock1.release()
print("A released lock1")
lock2.release()
print("A released lock2")
def fnB(lock1, lock2):
while True:
lock2.acquire()
print("B acquired lock2")
lock1.acquire()
print("B acquired lock1")
print("BBB")
lock2.release()
print("B released lock2")
lock1.release()
print("B released lock2")
if __name__ == "__main__":
lock1 = threading.Lock()
lock2 = threading.Lock()
threadA = threading.Thread(target=fnA, args=(lock1, lock2), daemon=True)
threadB = threading.Thread(target=fnB, args=(lock1, lock2), daemon=True)
threadA.start()
threadB.start()
threadA.join()
threadB.join()