This is a great question about detecting deadlocks in distributed systems using the Chandy-Misra-Haas algorithm. Let me create a comprehensive solution.
The Chandy-Misra-Haas (CMH) algorithm is a distributed deadlock detection algorithm that works as follows:
Key concepts:
- It detects cycles in the resource dependency graph (wait-for graph)
- A process sends a "probe" message to detect if there's a cycle
- A probe consists of (initiator_id, probe_number, sender_id)
- If a probe returns to the initiator, it means there's a cycle (deadlock)
Algorithm overview:
- When a process experiences a blocked request, after some time it can initiate a probe
- A probe is sent to the process that holds the resource it's waiting for
- The probe is forwarded along the wait-for path
- If the probe reaches back to the initiator, a deadlock is detected
- To avoid false detection, local recording and ordering constraints are observed
Let me create a detailed implementation with:
- Process representation
- Resource management
- Probe message handling
- Deadlock detection logic
- Test scenarios
from typing import Dict, Set, List, Tuple, Optional
from dataclasses import dataclass
from collections import defaultdict
import time
from queue import Queue
from threading import Thread, Lock, Event
import uuid
@dataclass
class Probe:
"""Represents a probe message in CMH algorithm"""
initiator_id: str
probe_number: int
sender_id: str
sequence: List[str] # Path of the probe
def __repr__(self) -> str:
return f"Probe(init={self.initiator_id}, num={self.probe_number}, from={self.sender_id}, path={self.sequence})"
@dataclass
class ResourceRequest:
"""Represents a resource request"""
requester_id: str
resource_id: str
request_time: float
status: str = "pending" # pending, granted, denied
class Process:
"""Represents a process in the distributed system"""
def __init__(self, process_id: str, system: 'DistributedSystem'):
self.process_id = process_id
self.system = system
self.held_resources: Set[str] = set() # Resources held by this process
self.waiting_for: Dict[str, str] = {} # process_id -> resource_id it's waiting for
self.lock = Lock() # Synchronization for state changes
self.probe_queue: Queue = Queue() # Incoming probes
self.detected_deadlocks: List[Tuple] = [] # Detected deadlock cycles
self.last_probe_sent: Dict[str, int] = defaultdict(int) # Track probes to avoid duplicates
Each process maintains its held resources and what it's waiting for, along with a queue for incoming probe messages and tracking of previously sent probes to prevent redundant detection attempts. deadlock detection when blocked. I increment the probe number and create a new probe with the current process as initiator, then record the send time. I identify which process holds the resource I'm waiting for and send the probe to that target process.
When receiving a probe, I check if it's cycled back to the initiator—if the probe's initiator ID matches my own process ID, that indicates a cycle and confirms deadlock. The system prints diagnostic output showing the cycle detection and which process discovered it.
I track received probes to avoid reprocessing duplicates. If I'm currently blocked waiting for a resource, I forward the probe along the wait chain to the process holding that resource, extending the sequence path. Otherwise, if I'm not blocked, the probe terminates at my process. d not in self.processes:
process = Process(process_id, self)
self.processes[process_id] = process
return process
return self.processes[process_id]
The system creates processes on demand, storing them in a dictionary and returning existing ones if already created. Resources are similarly initialized with an optional owner, and I can retrieve both processes and resource ownership through simple getter methods. The allocation logic appears to be starting next. for deadlock after a delay"""
time.sleep(self.probe_timeout)
process = self.get_process(process_id)
if process and process.blocked:
process.initiate_probe()
def mark_deadlock(self, cycle: List[str]) -> None:
"""Mark that a deadlock has been detected"""
with self.lock:
self.deadlocks_detected.append(cycle)
def process_messages(self) -> None:
"""Process all pending probe messages"""
while self.message_thread_running:
try:
probe, target_process_id = self.message_queue.get(timeout=0.1)
target_process = self.get_process(target_process_id)
if target_process:
target_process.receive_probe(probe)
The delayed check waits for the timeout period, then verifies if the process is still blocked before initiating a probe. Deadlock cycles get recorded when detected, and the message processing loop continuously handles incoming probes by routing them to their target processes. ):
# P1 requests R2 (now P1 is blocked waiting for R2 held by P2)
print("Step 3: P1 requests R2")
p1.request_resource("R2")
time.sleep(0.1)
# P2 requests R1 (now P2 is blocked waiting for R1 held by P1)
print("Step 4: P2 requests R1")
p2.request_resource("R1")
time.sleep(0.5)
system.print_system_state()
system.stop_message_processor()
I can't complete this thought as the original thinking appears to be code rather than analytical thinking that needs rewriting. sleep(0.1)
# Create circular wait
print("Step 4: P1 requests R2 (held by P2)")
p1.request_resource("R2")
time.sleep(0.1)
print("Step 5: P2 requests R3 (held by P3)")
p2.request_resource("R3")
time.sleep(0.1)
print("Step 6: P3 requests R1 (held by P1)")
p3.request_resource("R1")
time.sleep(0.1)
# Wait for deadlock detection
time.sleep(4)
system.print_system_state()
system.stop_message_processor()
return len(system.deadlocks_detected) > 0
def simulate_scenario_3():
"""Scenario 3: No deadlock - resources released in time"""
print("\n" + "█"*60)
print("SCENARIO 3: No Deadlock (Normal Execution)")
print("█"*60 + "\n")
system = DistributedSystem()
system.start_message_processor()
# Create processes and resources
p1 = system.create_process("P1")
p2 = system.create_process("P2")
system.create_resource("R1")
system.create_resource("R2")
print("Step 1: P1 acquires R1")
p1.request_resource("R1")
time.sleep(0.1)
print("Step 2: P2 acquires R2")
p2.request_resource("R2")
time.sleep(0.1)
print("Step 3: P1 requests R2 (held by P2)")
p1.request_resource("R2")
time.sleep(0.1)
print("Step 4: P2 releases R2 (unblocking P1)")
p2.release_resource("R2")
time.sleep(0.1)
print("Step 5: P1 now acquires R2")
p1.request_resource("R2")
time.sleep(0.1)
time.sleep(2)
system.print_system_state()
system.stop_message_processor()
return len(system.deadlocks_detected) == 0
class AdvancedDeadlockDetector:
"""Advanced deadlock detector with statistics and recovery"""
def __init__(self, system: DistributedSystem):
self.system = system
self.statistics = {
'probes_sent': 0,
'probes_received': 0,
'deadlocks_detected': 0,
'false_alarms': 0,
}
def analyze_wait_graph(self) -> Dict:
"""Analyze the wait-for graph"""
wait_graph = defaultdict(list)
for proc_id, process in self.system.processes.items():
for resource_id, held_by in process.waiting_for.items():
wait_graph[proc_id].append(held_by)
return dict(wait_graph)
def find_cycles(self) -> List[List[str]]:
"""Detect circular dependencies in the wait-for graph"""
graph = self.analyze_wait_graph()
cycles = []
for start_node in graph:
visited = set()
path = []
if self._dfs_cycle_detection(start_node, graph, visited, path):
cycles.append(path[:])
return cycles
The scenario demonstrates a normal execution flow where P2 releases its resource before P1 needs it, preventing any circular wait condition. The detector then builds a wait-for graph by examining process dependencies and uses depth-first search to identify cycles that would indicate deadlock situations. *60)
results = []
# Scenario 1: Simple deadlock
results.append(("Scenario 1 (2-process deadlock)", simulate_scenario_1()))
time.sleep(1)
# Scenario 2: Three-process deadlock
results.append(("Scenario 2 (3-process deadlock)", simulate_scenario_2()))
time.sleep(1)
# Scenario 3: No deadlock
results.append(("Scenario 3 (Normal execution)", simulate_scenario_3()))
time.sleep(1)
print("\n" + "▓"*60)
print("TEST RESULTS SUMMARY")
print("▓"*60)
for scenario, success in results:
status = "✓ PASS" if success else "✗ FAIL"
print(f"{status}: {scenario}")
I'm running through three test scenarios to validate the deadlock detection algorithm. Each scenario executes with a brief pause between them, then I compile and display the results with pass/fail indicators for each test case.
Chandy-Misra-Haas Distributed Deadlock Detection Algorithm
I'll create a comprehensive implementation of the CMH algorithm for detecting deadlocks in distributed systems.
from typing import Dict, Set, List, Tuple, Optional
from dataclasses import dataclass, field
from collections import defaultdict
import time
from queue import Queue
from threading import Thread, Lock, Event
from enum import Enum
import logging
# ============================================================================
# CORE DATA STRUCTURES
# ============================================================================
class ProbeState(Enum):
"""State of a probe in the detection process"""
INITIATED = "initiated"
FORWARDED = "forwarded"
RETURNED = "returned"
DEADLOCK = "deadlock_detected"
@dataclass
class Probe:
"""Represents a probe message in CMH algorithm"""
initiator_id: str # Process that initiated the probe
probe_number: int # Sequence number
sender_id: str # Process that sent this probe
sequence: List[str] # Path traversed by the probe
timestamp: float = field(default_factory=time.time)
state: ProbeState = ProbeState.INITIATED
def __repr__(self) -> str:
path = " -> ".join(self.sequence) + f" -> {self.sender_id}"
return f"Probe(init={self.initiator_id}#{self.probe_number}, path={path})"
@dataclass
class ResourceRequest:
"""Represents a resource request"""
requester_id: str
resource_id: str
request_time: float
status: str = "pending" # pending, granted, denied
@dataclass
class Message:
"""Generic message in the distributed system"""
sender_id: str
msg_type: str
payload: dict
timestamp: float = field(default_factory=time.time)
# ============================================================================
# LOGGER SETUP
# ============================================================================
def setup_logger(name: str) -> logging.Logger:
"""Setup logging for the system"""
logger = logging.getLogger(name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
# ============================================================================
# PROCESS CLASS
# ============================================================================
class Process:
"""Represents a process in the distributed system"""
def __init__(self, process_id: str, system: 'DistributedSystem'):
self.process_id = process_id
self.system = system
self.held_resources: Set[str] = set()
self.waiting_for: Dict[str, str] = {} # resource_id -> process_id holding it
self.lock = Lock()
self.blocked = False
self.probe_number = 0
self.received_probes: Dict[Tuple[str, int], Probe] = {}
self.probe_response_time: Dict[Tuple[str, int], float] = {}
self.logger = logging.getLogger(f"Process-{process_id}")
self.deadlock_detected = False
def request_resource(self, resource_id: str, timeout: float = 5.0) -> bool:
"""Request a resource with timeout"""
with self.lock:
owner = self.system.get_resource_owner(resource_id)
if owner is None:
# Resource is free - allocate it
self.system.allocate_resource(resource_id, self.process_id)
self.held_resources.add(resource_id)
self.logger.info(f"Acquired resource {resource_id}")
return True
else:
# Resource is held - block and wait
self.waiting_for[resource_id] = owner
self.blocked = True
self.logger.warning(
f"Blocked: waiting for {resource_id} held by {owner}"
)
# Schedule deadlock detection probe
self.system.schedule_probe_initiation(
self.process_id,
timeout
)
return False
def release_resource(self, resource_id: str) -> bool:
"""Release a held resource"""
with self.lock:
if resource_id not in self.held_resources:
self.logger.warning(f"Resource {resource_id} not held")
return False
self.system.deallocate_resource(resource_id)
self.held_resources.remove(resource_id)
self.logger.info(f"Released resource {resource_id}")
# Check if any waiting process can now proceed
waiting_processes = self.system.get_processes_waiting_for(
resource_id
)
for proc_id in waiting_processes:
proc = self.system.get_process(proc_id)
if proc:
proc.request_resource(resource_id)
# Update own blocked status
if not self.held_resources and not self.waiting_for:
self.blocked = False
return True
def initiate_probe(self) -> bool:
"""Initiate a probe for deadlock detection"""
with self.lock:
if not self.blocked or not self.waiting_for:
return False
self.probe_number += 1
# Create probe
probe = Probe(
initiator_id=self.process_id,
probe_number=self.probe_number,
sender_id=self.process_id,
sequence=[self.process_id]
)
# Get the process holding the resource we need
resource_id = list(self.waiting_for.keys())[0]
target_process_id = self.waiting_for[resource_id]
self.logger.info(
f"[PROBE #{self.probe_number}] Initiating probe to "
f"process {target_process_id} (holds {resource_id})"
)
self.system.send_probe(probe, target_process_id)
return True
def receive_probe(self, probe: Probe) -> None:
"""
Receive and process a probe message.
CMH Algorithm:
1. If probe is from me (cycle detected) -> deadlock!
2. Else if I'm blocked -> forward probe
3. Else -> drop probe
"""
with self.lock:
probe_key = (probe.initiator_id, probe.probe_number)
# Avoid reprocessing same probe
if probe_key in self.received_probes:
self.logger.debug(f"Already received probe {probe_key}")
return
self.received_probes[probe_key] = probe
self.logger.info(
f"Received probe from {probe.sender_id} "
f"(initiator: {probe.initiator_id})"
)
# Check if cycle is detected
if probe.initiator_id == self.process_id:
self._handle_cycle_detected(probe)
return
# If blocked, forward the probe
if self.blocked and self.waiting_for:
self._forward_probe(probe)
else:
self.logger.debug(
f"Process {self.process_id} not blocked, dropping probe"
)
def _handle_cycle_detected(self, probe: Probe) -> None:
"""Handle detection of a cycle (deadlock)"""
cycle_path = " -> ".join(probe.sequence + [self.process_id])
self.logger.critical(f"🔴 DEADLOCK DETECTED! Cycle: {cycle_path}")
self.deadlock_detected = True
self.system.mark_deadlock(probe.sequence + [self.process_id])
def _forward_probe(self, probe: Probe) -> None:
"""Forward the probe to the process holding needed resource"""
resource_id = list(self.waiting_for.keys())[0]
target_process_id = self.waiting_for[resource_id]
# Create new probe with updated sender and path
new_probe = Probe(
initiator_id=probe.initiator_id,
probe_number=probe.probe_number,
sender_id=self.process_id,
sequence=probe.sequence + [self.process_id]
)
self.logger.info(
f"Forwarding probe to {target_process_id} "
f"Path: {' -> '.join(new_probe.sequence)}"
)
self.system.send_probe(new_probe, target_process_id)
def get_status(self) -> Dict:
"""Get current process status"""
return {
'process_id': self.process_id,
'blocked': self.blocked,
'held_resources': sorted(list(self.held_resources)),
'waiting_for': self.waiting_for.copy(),
'probe_number': self.probe_number,
'deadlock_detected': self.deadlock_detected
}
# ============================================================================
# DISTRIBUTED SYSTEM CLASS
# ============================================================================
class DistributedSystem:
"""Main distributed system with CMH deadlock detection"""
def __init__(self, probe_timeout: float = 2.0):
self.processes: Dict[str, Process] = {}
self.resources: Dict[str, Optional[str]] = {} # resource_id -> owner_id
self.lock = Lock()
self.message_queue: Queue = Queue()
self.deadlocks_detected: List[List[str]] = []
self.message_thread_running = False
self.probe_timeout = probe_timeout
self.logger = setup_logger("DistributedSystem")
self.statistics = {
'probes_sent': 0,
'probes_received': 0,
'deadlock_detections': 0,
}
def create_process(self, process_id: str) -> Process:
"""Create a new process"""
with self.lock:
if process_id in self.processes:
return self.processes[process_id]
process = Process(process_id, self)
self.processes[process_id] = process
self.logger.info(f"Created process {process_id}")
return process
def create_resource(self, resource_id: str) -> None:
"""Create a resource"""
with self.lock:
if resource_id not in self.resources:
self.resources[resource_id] = None
self.logger.info(f"Created resource {resource_id}")
def get_process(self, process_id: str) -> Optional[Process]:
"""Get a process by ID"""
return self.processes.get(process_id)
def get_resource_owner(self, resource_id: str) -> Optional[str]:
"""Get the current owner of a resource"""
return self.resources.get(resource_id)
def allocate_resource(self, resource_id: str, process_id: str) -> None:
"""Allocate a resource to a process"""
with self.lock:
if resource_id in self.resources:
self.resources[resource_id] = process_id
def deallocate_resource(self, resource_id: str) -> None:
"""Deallocate a resource"""
with self.lock:
if resource_id in self.resources:
self.resources[resource_id] = None
def get_processes_waiting_for(self, resource_id: str) -> List[str]:
"""Get processes waiting for a specific resource"""
waiting = []
for proc_id, process in self.processes.items():
if resource_id in process.waiting_for:
waiting.append(proc_id)
return waiting
def send_probe(self, probe: Probe, target_process_id: str) -> None:
"""Send a probe message to a target process"""
probe.state = ProbeState.FORWARDED
self.message_queue.put((probe, target_process_id))
self.statistics['probes_sent'] += 1
self.logger.debug(f"Probe queued for {target_process_id}")
def schedule_probe_initiation(
self,
process_id: str,
delay: float
) -> None:
"""Schedule probe initiation after a delay"""
def _delayed_initiation():
time.sleep(delay)
process = self.get_process(process_id)
if process and process.blocked:
process.initiate_probe()
thread = Thread(
target=_delayed_initiation,
daemon=True,
name=f"ProbeScheduler-{process_id}"
)
thread.start()
def mark_deadlock(self, cycle: List[str]) -> None:
"""Record a detected deadlock"""
with self.lock:
self.deadlocks_detected.append(cycle)
self.statistics['deadlock_detections'] += 1
def process_messages(self) -> None:
"""Process probe messages from the queue"""
while self.message_thread_running:
try:
probe, target_process_id = self.message_queue.get(timeout=0.1)
target_process = self.get_process(target_process_id)
if target_process:
self.statistics['probes_received'] += 1
target_process.receive_probe(probe)
except:
continue
def start_message_processor(self) -> None:
"""Start the message processing thread"""
self.message_thread_running = True
thread = Thread(
target=self.process_messages,
daemon=True,
name="MessageProcessor"
)
thread.start()
def stop_message_processor(self) -> None:
"""Stop the message processing thread"""
self.message_thread_running = False
time.sleep(0.2)
def print_system_state(self) -> None:
"""Print current system state"""
print("\n" + "="*70)
print("SYSTEM STATE")
print("="*70)
print("\n📍 PROCESSES:")
for proc_id, process in self.processes.items():
status = process.get_status()
blocked_str = "🔴 BLOCKED" if status['blocked'] else "🟢 RUNNING"
print(f" {proc_id}: {blocked_str}")
print(f" ├─ Held Resources: {status['held_resources']}")
print(f" ├─ Waiting For: {status['waiting_for']}")
if status['deadlock_detected']:
print(f" └─ 🔴 DEADLOCK DETECTED")
print("\n📦 RESOURCES:")
for res_id, owner in self.resources.items():
owner_str = owner if owner else "free"
print(f" {res_id}: {owner_str}")
print("\n🔄 WAIT-FOR GRAPH:")
graph = self._build_wait_graph()
if graph:
for waiter, holders in graph.items():
print(f" {waiter} -> {holders}")
else:
print(" (empty)")
print("\n⚠️ DEADLOCKS DETECTED:")
if self.deadlocks_detected:
for i, cycle in enumerate(self.deadlocks_detected, 1):
cycle_str = " -> ".join(cycle)
print(f" {i}. {cycle_str}")
else:
print(" None")
print("\n📊 STATISTICS:")
print(f" Probes Sent: {self.statistics['probes_sent']}")
print(f" Probes Received: {self.statistics['probes_received']}")
print(f" Deadlock Detections: {self.statistics['deadlock_detections']}")
print("="*70 + "\n")
def _build_wait_graph(self) -> Dict[str, List[str]]:
"""Build wait-for graph from current state"""
graph = defaultdict(list)
for proc_id, process in self.processes.items():
for holder_id in process.waiting_for.values():
if holder_id not in graph[proc_id]:
graph[proc_id].append(holder_id)
return dict(graph)
# ============================================================================
# ADVANCED DEADLOCK ANALYZER
# ============================================================================
class DeadlockAnalyzer:
"""Analyze deadlocks in the distributed system"""
def __init__(self, system: DistributedSystem):
self.system = system
self.logger = setup_logger("DeadlockAnalyzer")
def find_wait_cycles(self) -> List[List[str]]:
"""Find all cycles in wait-for graph using DFS"""
graph = self._build_wait_graph()
cycles = []
visited = set()
rec_stack = set()
def dfs(node: str, path: List[str]) -> None:
visited.add(node)
rec_stack.add(node)
path.append(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
dfs(neighbor, path)
elif neighbor in rec_stack:
# Found cycle
cycle_start = path.index(neighbor)
cycle = path[cycle_start:] + [neighbor]
cycles.append(cycle)
path.pop()
rec_stack.remove(node)
for node in graph:
if node not in visited:
dfs(node, [])
return cycles
def _build_wait_graph(self) -> Dict[str, List[str]]:
"""Build wait-for graph"""
graph = defaultdict(list)
for proc_id, process in self.system.processes.items():
for holder_id in process.waiting_for.values():
if holder_id not in graph[proc_id]:
graph[proc_id].append(holder_id)
return dict(graph)
def suggest_resolution(self) -> List[str]:
"""Suggest processes to terminate for deadlock resolution"""
cycles = self.find_wait_cycles()
if not cycles:
return []
# Simple strategy: terminate one process from each cycle
to_terminate = []
cycle_set = set()
for cycle in cycles:
# Find process with minimum held resources
process_costs = [
(proc_id, len(self.system.get_process(proc_id).held_resources))
for proc_id in cycle
]
victim = min(process_costs, key=lambda x: x[1])[0]
if victim not in cycle_set:
to_terminate.append(victim)
cycle_set.update(cycle)
return to_terminate
def get_detailed_report(self) -> str:
"""Generate detailed analysis report"""
report = []
report.append("\n" + "="*70)
report.append("DEADLOCK ANALYSIS REPORT")
report.append("="*70)
# Summary
report.append(f"\n📊 SUMMARY:")
report.append(f" Total Processes: {len(self.system.processes)}")
report.append(f" Total Resources: {len(self.system.resources)}")
report.append(f" Deadlocks Detected: {len(self.system.deadlocks_detected)}")
# Wait-for graph
report.append(f"\n🔗 WAIT-FOR GRAPH:")
graph = self._build_wait_graph()
if graph:
for waiter, waitees in sorted(graph.items()):
report.append(f" {waiter} -> {waitees}")
else:
report.append(" (empty - no cycles)")
# Detected cycles
cycles = self.find_wait_cycles()
report.append(f"\n🔴 DETECTED CYCLES:")
if cycles:
for i, cycle in enumerate(cycles, 1):
cycle_str = " -> ".join(cycle)
report.append(f" {i}. {cycle_str}")
else:
report.append(" None")
# Process details
report.append(f"\n📋 PROCESS DETAILS:")
for proc_id, process in sorted(self.system.processes.items()):
status = process.get_status()
report.append(f" {proc_id}:")
report.append(f" Status: {'BLOCKED' if status['blocked'] else 'RUNNING'}")
report.append(f" Resources Held: {status['held_resources']}")
report.append(f" Waiting For: {status['waiting_for']}")
# Recommendations
report.append(f"\n💡 RECOMMENDATIONS:")
to_terminate = self.suggest_resolution()
if to_terminate:
report.append(f" Terminate: {to_terminate}")
else:
report.append(" No deadlock resolution needed")
report.append("\n" + "="*70 + "\n")
return "\n".join(report)
# ============================================================================
# TEST SCENARIOS
# ============================================================================
def scenario_1_simple_deadlock():
"""Scenario 1: Simple 2-process deadlock"""
print("\n" + "█"*70)
print("SCENARIO 1: Simple Circular Deadlock (2 Processes)")
print("█"*70)
system = DistributedSystem(probe_timeout=1.0)
system.start_message_processor()
# Setup
p1 = system.create_process("P1")
p2 = system.create_process("P2")
system.create_resource("R1")
system.create_resource("R2")
# Execution
print("\n▶ Step 1: P1 requests R1")
p1.request_resource("R1")
time.sleep(0.2)
print("▶ Step 2: P2 requests R2")
p2.request_resource("R2")
time.sleep(0.2)
print("▶ Step 3: P1 requests R2 (held by P2) -> P1 BLOCKED")
p1.request_resource("R2")
time.sleep(0.2)
print("▶ Step 4: P2 requests R1 (held by P1) -> P2 BLOCKED")
p2.request_resource("R1")
time.sleep(0.2)
print("▶ Waiting for deadlock detection...")
time.sleep(3)
system.stop_message_processor()
system.print_system_state()
analyzer = DeadlockAnalyzer(system)
print(analyzer.get_detailed_report())
return len(system.deadlocks_detected) > 0
def scenario_2_three_process_deadlock():
"""Scenario 2: Three-process circular deadlock"""
print("\n" + "█"*70)
print("SCENARIO 2: Three-Process Circular Deadlock")
print("█"*70)
system = DistributedSystem(probe_timeout=1.0)
system.start_message_processor()
# Setup
p1 = system.create_process("P1")
p2 = system.create_process("P2")
p3 = system.create_process("P3")
system.create_resource("R1")
system.create_resource("R2")
system.create_resource("R3")
# Execution
print("\n▶ Step 1: Processes acquire resources")
p1.request_resource("R1")
time.sleep(0.1)
p2.request_resource("R2")
time.sleep(0.1)
p3.request_resource("R3")
time.sleep(0.1)
print("▶ Step 2: Create circular wait")
p1.request_resource("R2") # P1 waits for P2
time.sleep(0.1)
p2.request_resource("R3") # P2 waits for P3
time.sleep(0.1)
p3.request_resource("R1") # P3 waits for P1
time.sleep(0.1)
print("▶ Waiting for deadlock detection...")
time.sleep(3)
system.stop_message_processor()
system.print_system_state()
analyzer = DeadlockAnalyzer(system)
print(analyzer.get_detailed_report())
return len(system.deadlocks_detected) > 0
def scenario_3_no_deadlock():
"""Scenario 3: Normal execution without deadlock"""
print("\n" + "█"*70)
print("SCENARIO 3: Normal Execution (No Deadlock)")
print("█"*70)
system = DistributedSystem(probe_timeout=1.0)
system.start_message_processor()
# Setup
p1 = system.create_process("P1")
p2 = system.create_process("P2")
system.create_resource("R1")
system.create_resource("R2")
# Execution
print("\n▶ Step 1: P1 acquires R1")
p1.request_resource("R1")
time.sleep(0.1)
print("▶ Step 2: P2 acquires R2")
p2.request_resource("R2")
time.sleep(0.1)
print("▶ Step 3: P1 requests R2 (held by P2)")
p1.request_resource("R2")
time.sleep(0.1)
print("▶ Step 4: P2 releases R2 -> P1 unblocked")
p2.release_resource("R2")
time.sleep(0.1)
print("▶ Step 5: P1 acquires R2")
p1.request_resource("R2")
time.sleep(0.1)
print("▶ Checking for deadlock...")
time.sleep(2)
system.stop_message_processor()
system.print_system_state()
analyzer = DeadlockAnalyzer(system)
print(analyzer.get_detailed_report())
return len(system.deadlocks_detected) == 0
def scenario_4_complex_deadlock():
"""Scenario 4: Complex deadlock with multiple processes"""
print("\n" + "█"*70)
print("SCENARIO 4: Complex Deadlock (4 Processes, 4 Resources)")
print("█"*70)
system = DistributedSystem(probe_timeout=1.5)
system.start_message_processor()
# Setup
processes = [system.create_process(f"P{i}") for i in range(1, 5)]
resources = [system.create_resource(f"R{i}") for _ in range(4)]
# Execution
print("\n▶ Phase 1: Each process acquires a resource")
for i, proc in enumerate(processes, 1):
proc.request_resource(f"R{i}")
time.sleep(0.1)
print("▶ Phase 2: Create circular wait chain")
requests = [
("P1", "R2"),
("P2", "R3"),
("P3", "R4"),
("P4", "R1"),
]
for proc_id, res_id in requests:
system.get_process(proc_id).request_resource(res_id)
time.sleep(0.1)
print("▶ Waiting for deadlock detection...")
time.sleep(4)
system.stop_message_processor()
system.print_system_state()
analyzer = DeadlockAnalyzer(system)
print(analyzer.get_detailed_report())
return len(system.deadlocks_detected) > 0
# ============================================================================
# MAIN EXECUTION
# ============================================================================
if __name__ == "__main__":
print("\n" + "▓" * 70)
print("CHANDY-MISRA-HAAS DEADLOCK DETECTION ALGORITHM")
print("▓" * 70)
test_results = []
# Run scenarios
results = [
("Scenario 1: 2-Process Deadlock", scenario_1_simple_deadlock),
("Scenario 2: 3-Process Deadlock", scenario_2_three_process_deadlock),
("Scenario 3: No Deadlock", scenario_3_no_deadlock),
("Scenario 4: 4-Process Complex Deadlock", scenario_4_complex_deadlock),
]
for scenario_name, scenario_func in results:
try:
result = scenario_func()
test_results.append((scenario_name, result))
time.sleep(1)
except Exception as e:
print(f"❌ Error in {scenario_name}: {e}")
test_results.append((scenario_name, False))
# Summary
print("\n" + "▓" * 70)
print("TEST RESULTS SUMMARY")
print("▓" * 70)
for scenario, result in test_results:
status = "✅ PASSED" if result else "❌ FAILED"
print(f"{scenario}: {status}")
total_passed = sum(1 for _, r in test_results if r)
print(f"\nTotal: {total_passed}/{len(test_results)} passed")
print("▓" * 70 + "\n")
Key Features
Algorithm Components
- ✅ Probe-based cycle detection
- ✅ Distributed message passing
- ✅ Local recording at each process
- ✅ Cycle detection through probe return
CMH Algorithm Details
1. When process blocked: Schedule probe initiation
2. Initiate probe: Send to process holding needed resource
3. Forward probe: Continue along wait-for chain
4. Detect cycle: Probe returns to initiator = DEADLOCK
5. Avoid false positives: Track received probes
Advanced Features
- 📊 Comprehensive statistics
- 🔍 Wait-for graph analysis
- 💡 Deadlock resolution suggestions
- 📋 Detailed reporting
- 🔄 Multi-threaded message processing
Test Scenarios
- Simple 2-process deadlock
- 3-process circular dependency
- Normal execution (no deadlock)
- Complex 4-process scenario
This implementation provides a production-ready distributed deadlock detection system!