Skip to content

Commit 44324da

Browse files
committed
Threading\S03-Race-Condition\S03-01-race-condition
1 parent c078358 commit 44324da

File tree

1 file changed

+34
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)