-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDekkersAlgorithm.py
More file actions
68 lines (56 loc) · 1.48 KB
/
DekkersAlgorithm.py
File metadata and controls
68 lines (56 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import threading
import time
# Shared variables
flag = [False, False]
turn = 0
def process_0():
global turn
for i in range(3):
# Entry section
flag[0] = True
while flag[1]:
if turn != 0:
flag[0] = False
while turn != 0:
pass # busy wait
flag[0] = True
# ---- Critical Section ----
print("Process 0: Entering critical section")
time.sleep(1)
print("Process 0: Leaving critical section")
# --------------------------
# Exit section
turn = 1
flag[0] = False
# Remainder section
time.sleep(0.5)
def process_1():
global turn
for i in range(3):
# Entry section
flag[1] = True
while flag[0]:
if turn != 1:
flag[1] = False
while turn != 1:
pass # busy wait
flag[1] = True
# ---- Critical Section ----
print("Process 1: Entering critical section")
time.sleep(1)
print("Process 1: Leaving critical section")
# --------------------------
# Exit section
turn = 0
flag[1] = False
# Remainder section
time.sleep(0.5)
# Create two threads simulating two processes
t1 = threading.Thread(target=process_0)
t2 = threading.Thread(target=process_1)
# Start both threads
t1.start()
t2.start()
# Wait for both to finish
t1.join()
t2.join()