Skip to content

Commit d9a092b

Browse files
committed
Threading\S03-Race-Condition\S03-03-Lock-in-Class
1 parent 5351aae commit d9a092b

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from threading import Thread, Lock
2+
from time import sleep
3+
4+
5+
class Counter:
6+
def __init__(self):
7+
self.value = 0
8+
self.lock = Lock()
9+
10+
def increase(self, by):
11+
self.lock.acquire()
12+
13+
current_value = self.value
14+
current_value += by
15+
16+
sleep(0.1)
17+
18+
self.value = current_value
19+
print(f'counter={self.value}')
20+
21+
self.lock.release()
22+
23+
24+
counter = Counter()
25+
26+
# create threads
27+
t1 = Thread(target=counter.increase, args=(10, ))
28+
t2 = Thread(target=counter.increase, args=(20, ))
29+
30+
# start the threads
31+
t1.start()
32+
t2.start()
33+
34+
35+
# wait for the threads to complete
36+
t1.join()
37+
t2.join()
38+
39+
40+
print(f'The final counter is {counter.value}')

0 commit comments

Comments
 (0)