-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_semaphore.py
More file actions
152 lines (118 loc) · 5.48 KB
/
binary_semaphore.py
File metadata and controls
152 lines (118 loc) · 5.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import threading
import time
import pygame
import sys
from main import VisualizationApp
# Define colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (169, 169, 169) # Gray color for the semaphore gate when value is 0
RED = (255, 0, 0)
BLACK = (0, 0, 0)
class SemaphoreDemo:
def __init__(self, main_app):
pygame.init()
self.main_app = main_app
self.width = 800
self.height = 500
self.screen = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption("Semaphore Demo")
self.character_positions = [(100, 150), (300, 150), (500, 150)]
self.character_names = ['A', 'B', 'C'] # Character names
self.character_speed = 5
# Initialize binary semaphore with value 1
self.semaphore = threading.Semaphore(1)
self.semaphore_value = 1 # Initial semaphore value
self.locked_flags = [False] * len(self.character_positions)
self.current_event = "" # Store the current event message
self.font = pygame.font.SysFont(None, 30)
self.small_font = pygame.font.SysFont(None, 24)
self.clock = pygame.time.Clock()
self.create_threads()
def create_threads(self):
for i, (x, y) in enumerate(self.character_positions):
thread = threading.Thread(target=self.thread_func, args=(i,))
thread.daemon = True # Set threads as daemons to allow proper termination
thread.start()
def thread_func(self, index):
while True:
with self.semaphore:
# Lock the character
self.semaphore_value = 0 # Update semaphore value to 0 when acquired
self.locked_flags[index] = True
# Update the current event message
self.current_event = f"Locked by Thread {self.character_names[index]}"
time.sleep(0.5)
# Move the character
self.character_positions[index] = (self.character_positions[index][0] + self.character_speed, self.character_positions[index][1])
time.sleep(0.5)
# Unlock the character
self.semaphore_value = 1 # Update semaphore value to 1 when released
self.locked_flags[index] = False
# Update the current event message
self.current_event = f"Released by Thread {self.character_names[index]}"
time.sleep(0.5)
time.sleep(1)
def draw_scene(self):
self.screen.fill(WHITE)
# Determine the color of the semaphore gate based on its value
semaphore_color = GRAY if self.semaphore_value == 0 else GREEN
# Draw semaphore gate
pygame.draw.rect(self.screen, semaphore_color, (350, 10, 100, 50))
self.draw_text(f"Semaphore Value: {self.semaphore_value}", 340, 70)
# Draw characters (threads) and their names
for i, (x, y) in enumerate(self.character_positions):
# Draw character
pygame.draw.rect(self.screen, BLUE, (x, y, 50, 50))
# Draw character name
self.draw_text(self.character_names[i], x + 20, y + 20)
# Draw lock/unlock indicator
if self.locked_flags[i]:
pygame.draw.rect(self.screen, RED, (x + 20, y - 30, 10, 10)) # Draw red square when locked
# Draw the current event message
self.draw_text(self.current_event, 10, 10)
# Instructions for quitting
self.draw_text("Press 'Q' to quit, 'R' to return to main page", 10, 470)
# Explanation text
explanation = [
"Blue boxes represent threads, each running independently.",
"Green gate represents the binary semaphore concept.",
"Binary semaphore ensures that only one thread can access shared resources at a time,",
"preventing conflicts and ensuring data integrity.",
"When a thread acquires a binary semaphore, it decrements its value by 1.",
"If the semaphore's value is already 0 when a thread tries to acquire it,",
"the thread will be blocked until the semaphore's value becomes nonzero.",
"When the semaphore is released, its value is incremented by 1."
]
y_offset = 250
for line in explanation:
self.draw_text(line, 10, y_offset, color=BLACK, font=self.small_font)
y_offset += 20
pygame.display.flip()
def draw_text(self, text, x, y, color=BLACK, font=None):
if font is None:
font = self.font
text_surface = font.render(text, True, color)
self.screen.blit(text_surface, (x, y))
def run(self):
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
running = False
elif event.key == pygame.K_r:
self.main_app.run()
# Draw scene
self.draw_scene()
self.clock.tick(60)
# Quit pygame before exiting the program
pygame.quit()
sys.exit()
if __name__ == "__main__":
app = VisualizationApp()
demo = SemaphoreDemo(app)
demo.run()