Skip to content

Commit 996b711

Browse files
committed
RLock
1 parent 0971e95 commit 996b711

1 file changed

Lines changed: 43 additions & 0 deletions

File tree

src/threat_rlock.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Race condition
3+
Thread safe
4+
Dead lock
5+
atomic
6+
"""
7+
from threading import Thread, RLock
8+
9+
num = 0 # shared resource
10+
lock = RLock()
11+
12+
13+
def add():
14+
global num
15+
with lock:
16+
subtract()
17+
for _ in range(100000):
18+
num += 1
19+
20+
21+
def subtract():
22+
global num
23+
with lock:
24+
for _ in range(100000):
25+
num -= 1
26+
27+
28+
def both():
29+
subtract()
30+
add()
31+
32+
33+
t1 = Thread(target=add)
34+
t2 = Thread(target=subtract)
35+
36+
t1.start()
37+
t2.start()
38+
39+
t1.join()
40+
t2.join()
41+
42+
print(num)
43+
print('Done . . . ')

0 commit comments

Comments
 (0)