Skip to content

Commit 6a43860

Browse files
committed
Threading\S03-Race-Condition\S03-04-Gil-stop-race-condition
1 parent d9a092b commit 6a43860

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+
import threading
2+
import time
3+
4+
# global variable x
5+
x = 0
6+
7+
def thread_task(n):
8+
global x
9+
for _ in range(n):
10+
x += 1 # critical section : Gil Can Stop Race Condition(Only one thread can run at a time)
11+
time.sleep(0.0001)
12+
13+
14+
def main_task():
15+
global x
16+
# setting global variable x as 0
17+
x = 0
18+
19+
# creating threads
20+
t1 = threading.Thread(target=thread_task, args=(100, ))
21+
t2 = threading.Thread(target=thread_task, args=(100, ))
22+
23+
# start threads
24+
t1.start()
25+
t2.start()
26+
27+
# wait until threads finish their job
28+
t1.join()
29+
t2.join()
30+
31+
if __name__ == "__main__":
32+
for i in range(10):
33+
main_task()
34+
print("Iteration {0}: x = {1}".format(i,x))

0 commit comments

Comments
 (0)