File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
Threading/S03-Race-Condition Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 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 } ' )
You can’t perform that action at this time.
0 commit comments