DC Exp 8
DC Exp 8
Program Code :
import threading
import time
import random
from collections import defaultdict
# Number of processes and resources
N=5
MAX_ITERATIONS = 3 # Each process will try to access resources up to this limit
# Wait-for graph
wait_for_graph = defaultdict(set)
graph_lock = threading.Lock()
stack.remove(node)
return False
visited = set()
for process in range(N):
if process not in visited:
if has_cycle(process, visited, set()):
return True
return False
# Request resource
with resource_lock:
if resources[resource_id] == 0:
# Allocate resource if available
resources[resource_id] = process_id
print(f"Process {process_id} allocated resource {resource_id}")
time.sleep(random.uniform(0.5, 1)) # Simulate work
# Release resource
resources[resource_id] = 0
print(f"Process {process_id} released resource {resource_id}")
else:
# Add process to wait-for graph
with graph_lock:
wait_for_graph[process_id].add(resources[resource_id])