Arpit Chaudhary - DS - LAB - FILE
Arpit Chaudhary - DS - LAB - FILE
Bachelors of Technology
In Computer Science and
Engineering
Submitted to Submitted by
1
INDEX
2
EXPERIMENT 1
#include <stdio.h>
#include <stdlib.h>
int events[MAX_EVENTS];
printf("Enter the dependencies for each event (0 if independent):\n");
for (int i = 0; i < n; i++) {
printf("Event E%d: ", i + 1);
scanf("%d", &events[i]);
}
lamport_logical_clock(events, n);
return 0;
}
4
Output:
5
EXPERIMENT 2
int main() {
int n, vc[MAX][MAX], choice, p1, p2;
initialize(vc, n);
while (1) {
printf("\n1. Internal Event\n2. Message Event\n3. Display Clock\n4.
Exit\nChoice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter process ID (1 to %d): ", n);
scanf("%d", &p1);
if (p1 < 1 || p1 > n) {
printf("Invalid process ID!\n");
} else {
internal_event(vc, p1 - 1);
}
break;
case 2:
printf("Enter sender and receiver IDs (1 to %d): ", n);
7
scanf("%d %d", &p1, &p2);
if (p1 < 1 || p1 > n || p2 < 1 || p2 > n) {
printf("Invalid process IDs!\n");
} else {
message_event(vc, p1 - 1, p2 - 1, n);
}
break;
case 3:
display(vc, n);
break;
case 4:
return 0;
default:
printf("Invalid choice!\n");
}
}
return 0;
}
8
Output:
9
EXPERIMENT 3
import java.util.Scanner;
10
// Grant access to the critical section
public static void grantCriticalSection(int process) {
boolean canEnter = true;
for (int i = 0; i < totalProcesses; i++) {
if (i != process && requestQueue[i]) {
canEnter = false;
break;
}
}
if (canEnter) {
enterCriticalSection(process);
} else {
System.out.println("Process " + process + " is waiting for
replies...");
}
}
11
leaveCriticalSection(process);
}
12
// Initialize request and reply queues
for (int i = 0; i < MAX_PROCESSES; i++) {
requestQueue[i] = false;
replyQueue[i] = false;
}
while (true) {
System.out.print("\n1. Request Critical Section\n2.
Exit\nEnter your choice: ");
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter process ID (0 to " +
(totalProcesses - 1) + "): ");
processId = scanner.nextInt();
if (processId < 0 || processId >= totalProcesses) {
System.out.println("Invalid process ID.");
} else if (criticalSection) {
System.out.println("Critical section is currently
occupied. Try again later.");
} else {
requestCriticalSection(processId);
}
break;
case 2:
System.out.println("Exiting...");
scanner.close();
return;
default:
13
System.out.println("Invalid choice. Please try again.");
}
}
}
}
14
EXPERIMENT 4
Step 1: Hello.idl
module HelloApp {
interface Hello {
string sayHello();
};
};
Step 2: HelloServer.java
import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;
import org.omg.PortableServer.POA;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
16
Step 3: HelloClient.java
import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
} catch (Exception e) {
e.printStackTrace();
}
}
17
EXPERIMENT 5
18
if path not in paths[destination] or paths[destination][path] >
new_cost:
paths[destination][path] = new_cost
updated = True
if __name__ == "__main__":
vertices = int(input("Enter the number of vertices: "))
edges = int(input("Enter the number of edges: "))
graph = Graph(vertices)
19
Output:
20
EXPERIMENT 6
visited.add(self.pid)
visited.remove(self.pid) # Backtrack
return False
if __name__ == "__main__":
# Create processes
num_processes = int(input("Enter the number of processes: "))
processes = {i: Process(i) for i in range(num_processes)}
# Add dependencies
print("Enter dependencies (process waiting for another process). Enter -
1 -1 to stop:")
21
while True:
p1, p2 = map(int, input().split())
if p1 == -1 and p2 == -1:
break
processes[p1].add_dependency(processes[p2])
Output:
22
EXPERIMENT 7
import random
class Participant:
def __init__(self, pid):
self.pid = pid
self.vote = None # 'commit' or 'abort'
def decide_vote(self):
self.vote = random.choice(['commit', 'abort'])
print(f"Participant {self.pid} votes {self.vote}")
return self.vote
class Coordinator:
def __init__(self, participants):
self.participants = participants
def two_phase_commit(self):
print("\nPhase 1: Voting Phase")
votes = []
for participant in self.participants:
votes.append(participant.decide_vote())
if 'abort' in votes:
print("\nPhase 2: Abort Phase")
print("Coordinator instructs all participants to ROLLBACK.")
self.rollback()
else:
print("\nPhase 2: Commit Phase")
23
print("Coordinator instructs all participants to COMMIT.")
self.commit()
def commit(self):
for participant in self.participants:
print(f"Participant {participant.pid} commits transaction.")
def rollback(self):
for participant in self.participants:
print(f"Participant {participant.pid} rolls back transaction.")
if __name__ == "__main__":
num_participants = int(input("Enter the number of participants: "))
participants = [Participant(pid) for pid in range(num_participants)]
coordinator = Coordinator(participants)
coordinator.two_phase_commit()
Output
24
EXPERIMENT 8
class Participant:
def __init__(self, pid):
self.pid = pid
self.vote = None # 'yes' or 'no'
def cast_vote(self):
# Randomly choose 'yes' or 'no'
self.vote = random.choice(['yes', 'no'])
print(f"Participant {self.pid} votes {self.vote}")
return self.vote
class Coordinator:
def __init__(self, participants):
self.participants = participants
def execute_voting_protocol(self):
print("\nVoting Phase:")
votes = []
for participant in self.participants:
votes.append(participant.cast_vote())
# Decision Phase
print("\nDecision Phase:")
if 'no' in votes:
print("Consensus not achieved. The proposal is REJECTED.")
else:
25
print("Consensus achieved. The proposal is ACCEPTED.")
if __name__ == "__main__":
num_participants = int(input("Enter the number of participants: "))
participants = [Participant(pid) for pid in range(num_participants)]
coordinator = Coordinator(participants)
coordinator.execute_voting_protocol()
Output:
26