from machine import Pin, I2C
from time import ticks_ms, ticks_diff, sleep_ms
from pico_i2c_lcd import I2cLcd
# ------------------------------------------------------------
# OS Concurrency Simulator
# Raspberry Pi Pico / MicroPython / Wokwi
#
# Scenario:
# Four cars represent concurrent tasks.
# One narrow bridge represents a shared resource.
#
# Demonstrates:
# - Concurrency
# - Shared resources
# - Coordination
# - Synchronization
# - Mutex locking
# - Race conditions
#
# Student enhancement ideas:
# - Disable the lock to demonstrate a race condition
# - Add priority scheduling
# - Add starvation detection
# - Add deadlock simulation
# ------------------------------------------------------------
CAR_BUTTON_PINS = [10, 11, 12, 13]
CAR_LED_PINS = [2, 3, 4, 5]
LCD_ADDRESS = 0x27
LCD_ROWS = 2
LCD_COLS = 16
CROSSING_TIME_MS = 4000
BLINK_INTERVAL_MS = 250
DEBOUNCE_MS = 180
MAX_WAITING = 8
# Set to False to intentionally demonstrate a race condition.
LOCK_ENABLED = True
car_names = ["A", "B", "C", "D"]
buttons = [
Pin(pin, Pin.IN, Pin.PULL_UP)
for pin in CAR_BUTTON_PINS
]
leds = [
Pin(pin, Pin.OUT, value=0)
for pin in CAR_LED_PINS
]
i2c = I2C(
0,
sda=Pin(0),
scl=Pin(1),
freq=400000
)
lcd = I2cLcd(
i2c,
LCD_ADDRESS,
LCD_ROWS,
LCD_COLS
)
# Queue items:
# {
# "car": 0..3,
# "arrival": ticks_ms()
# }
waiting_queue = []
# With locking enabled, only one task may use the bridge.
bridge_locked = False
crossing_tasks = []
last_button_times = [0, 0, 0, 0]
last_blink_time = 0
blink_state = False
last_lcd_text = None
completed_count = 0
race_condition_count = 0
def pad(text):
"""Return a string exactly LCD_COLS characters long."""
return (text + " " * LCD_COLS)[:LCD_COLS]
def is_car_active(car_index):
"""Return True if the car is waiting or crossing."""
for task in waiting_queue:
if task["car"] == car_index:
return True
for task in crossing_tasks:
if task["car"] == car_index:
return True
return False
def add_car(car_index, now):
"""Add a new concurrent task to the waiting queue."""
if is_car_active(car_index):
print("IGNORED: Car {} is already waiting or crossing".format(
car_names[car_index]
))
return
if len(waiting_queue) >= MAX_WAITING:
print("QUEUE FULL: Car {} rejected".format(
car_names[car_index]
))
return
task = {
"car": car_index,
"arrival": now
}
waiting_queue.append(task)
leds[car_index].on()
print("ARRIVAL: Car {} entered the waiting queue".format(
car_names[car_index]
))
print_queue()
def start_crossing(now):
"""
Start one or more crossing tasks.
LOCK_ENABLED = True:
Only one task can acquire the bridge.
LOCK_ENABLED = False:
All waiting tasks may enter, causing a race condition.
"""
global bridge_locked, race_condition_count
if LOCK_ENABLED:
if bridge_locked or not waiting_queue:
return
task = waiting_queue.pop(0)
task["start"] = now
crossing_tasks.append(task)
bridge_locked = True
print("LOCK ACQUIRED: Car {} entered the bridge".format(
car_names[task["car"]]
))
else:
# Intentional race-condition demonstration:
# every waiting task enters the bridge without mutual exclusion.
while waiting_queue:
task = waiting_queue.pop(0)
task["start"] = now
crossing_tasks.append(task)
print("UNSAFE ACCESS: Car {} entered the bridge".format(
car_names[task["car"]]
))
if len(crossing_tasks) > 1:
race_condition_count += 1
print("RACE CONDITION: Multiple cars are on the bridge!")
def update_crossing(now):
"""Blink crossing LEDs and complete finished tasks."""
global last_blink_time, blink_state
global bridge_locked, completed_count
if not crossing_tasks:
return
if ticks_diff(now, last_blink_time) >= BLINK_INTERVAL_MS:
blink_state = not blink_state
for task in crossing_tasks:
leds[task["car"]].value(blink_state)
last_blink_time = now
finished = []
for task in crossing_tasks:
if ticks_diff(now, task["start"]) >= CROSSING_TIME_MS:
finished.append(task)
for task in finished:
crossing_tasks.remove(task)
leds[task["car"]].off()
completed_count += 1
print("COMPLETED: Car {} crossed the bridge".format(
car_names[task["car"]]
))
if LOCK_ENABLED and not crossing_tasks:
bridge_locked = False
print("LOCK RELEASED: Bridge is available")
def update_waiting_leds():
"""Keep waiting cars solid ON."""
crossing_cars = [task["car"] for task in crossing_tasks]
for task in waiting_queue:
if task["car"] not in crossing_cars:
leds[task["car"]].on()
def current_bridge_text():
"""Return a compact description of cars on the bridge."""
if not crossing_tasks:
return "Bridge: FREE"
names = "".join(
car_names[task["car"]]
for task in crossing_tasks
)
return "Bridge:" + names
def update_lcd():
"""Display bridge and queue status."""
global last_lcd_text
line1 = current_bridge_text()
line2 = "Wait:{} Done:{}".format(
len(waiting_queue),
completed_count
)
text = (line1, line2)
if text != last_lcd_text:
lcd.move_to(0, 0)
lcd.putstr(pad(line1))
lcd.move_to(0, 1)
lcd.putstr(pad(line2))
last_lcd_text = text
def print_queue():
"""Print waiting queue order."""
if not waiting_queue:
print("WAITING QUEUE: empty")
return
names = [
car_names[task["car"]]
for task in waiting_queue
]
print("WAITING QUEUE:", " -> ".join(names))
def initialize():
lcd.clear()
lcd.move_to(0, 0)
lcd.putstr(pad("Concurrency Lab"))
lcd.move_to(0, 1)
if LOCK_ENABLED:
lcd.putstr(pad("Mutex Enabled"))
else:
lcd.putstr(pad("Unsafe Mode"))
sleep_ms(1500)
lcd.clear()
print("OS Concurrency Bridge Simulator")
print("Buttons GP10-GP13: Cars A-D")
print("LED ON: waiting")
print("LED BLINK: crossing")
print("LED OFF: idle/completed")
print("LOCK_ENABLED =", LOCK_ENABLED)
if LOCK_ENABLED:
print("Synchronization active: only one car may cross")
else:
print("Synchronization disabled: race condition possible")
initialize()
while True:
now = ticks_ms()
for car_index, button in enumerate(buttons):
if (
button.value() == 0
and ticks_diff(
now,
last_button_times[car_index]
) >= DEBOUNCE_MS
):
add_car(car_index, now)
last_button_times[car_index] = now
while button.value() == 0:
sleep_ms(10)
start_crossing(now)
update_crossing(now)
update_waiting_leds()
update_lcd()
sleep_ms(10)
ON = WAITING BLINK = CROSSING OFF = IDLE
OS Concurrency: Shared Bridge + Mutex