0% found this document useful (0 votes)
9 views21 pages

DS - LabFile Chirag

The document is a lab file for a Distributed Systems course, detailing various programming experiments conducted by a student named Chirag Mittal. It includes objectives and implementations for algorithms such as Lamport's Logical Clock, Vector Clock, Distributed Mutual Exclusion, CORBA, Path Pushing, Edge Chasing, Commit Protocol, and Voting Protocol. Each experiment provides code examples in C, Java, or Python, demonstrating the functionality of distributed systems concepts.

Uploaded by

cm2810451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views21 pages

DS - LabFile Chirag

The document is a lab file for a Distributed Systems course, detailing various programming experiments conducted by a student named Chirag Mittal. It includes objectives and implementations for algorithms such as Lamport's Logical Clock, Vector Clock, Distributed Mutual Exclusion, CORBA, Path Pushing, Edge Chasing, Commit Protocol, and Voting Protocol. Each experiment provides code examples in C, Java, or Python, demonstrating the functionality of distributed systems concepts.

Uploaded by

cm2810451
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

DISTRIBUTED SYSTEMS LAB FILE

(KCS751A)

Name: Chirag Mittal


Roll. No.: 2102300100057
College Roll No.: 16059
Year: 4th Year
Branch: CSE
INDEX

Sno. Name Of Program Page No. Remarks


WAP to simulate the
functionality of Lamport's
1 Logical clock in C.

WAP to Implement Vector


clock in C.
2

Simulation of Distributed
mutual exclusion in java.
3

Implementation of CORBA
(Common Object Request
4 Broker Architecture)
mechanism.

Implementation of Path
Pushing Algorithm
5

Implementation of Edge
Chasing Algorithm
6
Implementation of Commit
Protocol Algorithm
7

Implementation of Voting
Protocol Algorithm
8
EXPERIMENT 1

Objective: WAP to simulate the functionality of Lamport's


Logical clock in C.

#include <stdio.h>
#include <stdlib.h>

#define MAX_EVENTS 100

int max(int a, int b) {


return (a > b) ? a : b;
}

void lamport_logical_clock(int events[], int n) {


int logical_clock[MAX_EVENTS] = {0}; // Array to store logical clock
values

logical_clock[0] = 1;

for (int i = 1; i < n; i++) {


logical_clock[i] = max(logical_clock[i - 1], events[i]) + 1;
}
printf("\nEvent\tTimestamp\n");
for (int i = 0; i < n; i++) {
printf("E%d\t%d\n", i + 1, logical_clock[i]);
}
}

int main() {
int n;

printf("Enter the number of events: ");


scanf("%d", &n);

if (n <= 0 || n > MAX_EVENTS) {


printf("Invalid number of events. Please enter a value between 1
and %d.\n", MAX_EVENTS);
return -1;
}
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;
}

Output:
EXPERIMENT 2

Objective: WAP to Implement Vector clock in C.

#include <stdio.h>
#define MAX 10

void initialize(int vc[MAX][MAX], int n) {


for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
vc[i][j] = 0;
}

void display(int vc[MAX][MAX], int n) {


printf("\nVector Clock:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", vc[i][j]);
}
printf("\n");
}
}

void internal_event(int vc[MAX][MAX], int pid) {


vc[pid][pid]++;
}

void message_event(int vc[MAX][MAX], int sender, int receiver, int n) {


vc[sender][sender]++;
for (int i = 0; i < n; i++)
vc[receiver][i] = (vc[receiver][i] > vc[sender][i]) ?
vc[receiver][i] : vc[sender][i];
vc[receiver][receiver]++;
}

int main() {
int n, vc[MAX][MAX], choice, p1, p2;

printf("Enter number of processes (max %d): ", MAX);


scanf("%d", &n);
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: ");
scanf("%d", &p1);
internal_event(vc, p1 - 1);
break;
case 2:
printf("Enter sender and receiver IDs: ");
scanf("%d %d", &p1, &p2);
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;
}

Output:
EXPERIMENT 3

Objective: Simulation of Distributed mutual exclusion in


java.

import java.util.Scanner;

public class DistributedMutex {


private static final int MAX_PROCESSES = 10;
private static boolean[] requestQueue = new boolean[MAX_PROCESSES];
private static boolean[] replyQueue = new boolean[MAX_PROCESSES];
private static boolean criticalSection = false;
private static int processId;
private static int totalProcesses;

// Request access to the critical section


public static void requestCriticalSection(int process) {
System.out.println("Process " + process + " is requesting critical
section...");
for (int i = 0; i < totalProcesses; i++) {
if (i != process) {
System.out.println("Process " + process + " sends REQUEST
to Process " + i);
requestQueue[i] = true;
}
}
grantCriticalSection(process);
}

// 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...");
}
}

// Enter the critical section


public static void enterCriticalSection(int process) {
criticalSection = true;
System.out.println("Process " + process + " enters the critical
section.");
try {
Thread.sleep(2000); // Simulate some work in the critical
section
} catch (InterruptedException e) {
e.printStackTrace();
}
leaveCriticalSection(process);
}

// Leave the critical section


public static void leaveCriticalSection(int process) {
System.out.println("Process " + process + " leaves the critical
section.");
criticalSection = false;
for (int i = 0; i < totalProcesses; i++) {
if (i != process && requestQueue[i]) {
System.out.println("Process " + process + " sends REPLY to
Process " + i);
replyQueue[i] = true;
}
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input number of processes


System.out.print("Enter the number of processes (max " +
MAX_PROCESSES + "): ");
totalProcesses = scanner.nextInt();
if (totalProcesses <= 0 || totalProcesses > MAX_PROCESSES) {
System.out.println("Invalid number of processes.");
return;
}

// 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:
System.out.println("Invalid choice. Please try
again.");
}
}
}
}
EXPERIMENT 4

Objective: Implementation of CORBA (Common Object


Request Broker Architecture) mechanism.

Step 1: Hello.idl
module HelloApp {
interface Hello {
string sayHello();
};
};

Step 2: HelloServer.java
import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.PortableServer.*;

public class HelloServer {


public static void main(String[] args) {
try {
// Initialize ORB
ORB orb = ORB.init(args, null);

// Get reference to RootPOA and activate POAManager


POA rootPOA =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootPOA.the_POAManager().activate();

// Create servant and register with ORB


HelloServant helloRef = new HelloServant();
org.omg.CORBA.Object ref =
rootPOA.servant_to_reference(helloRef);
Hello helloRefHello = HelloHelper.narrow(ref);

// Bind the object reference in the Naming Service


org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef =
NamingContextExtHelper.narrow(objRef);
NameComponent[] path = ncRef.to_name("Hello");
ncRef.rebind(path, helloRefHello);

System.out.println("HelloServer ready and waiting...");

// Keep server running


orb.run();

} catch (Exception e) {
e.printStackTrace();
}
}
}

class HelloServant extends HelloPOA {


public String sayHello() {
return "Hello from CORBA Server!";
}
}

Step 3: HelloClient.java
import HelloApp.*;
import org.omg.CORBA.*;
import org.omg.CosNaming.*;

public class HelloClient {


public static void main(String[] args) {
try {
// Initialize ORB
ORB orb = ORB.init(args, null);

// Get reference to Naming Service


org.omg.CORBA.Object objRef =
orb.resolve_initial_references("NameService");
NamingContextExt ncRef =
NamingContextExtHelper.narrow(objRef);

// Resolve the object reference


Hello helloRef =
HelloHelper.narrow(ncRef.resolve_str("Hello"));

// Call the method on the server


String response = helloRef.sayHello();
System.out.println("Response from server: " + response);

} catch (Exception e) {
e.printStackTrace();
}
}
}
EXPERIMENT 5

Objective: Implementation of Path Pushing Algorithm

class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.edges = []

def add_edge(self, source, destination, weight):


self.edges.append((source, destination, weight))

def path_pushing_algorithm(self, start_vertex):


# Initialize distance table
paths = {v: {} for v in range(self.vertices)}
paths[start_vertex][start_vertex] = 0

# Repeat path pushing until no updates


updated = True
while updated:
updated = False
for source, destination, weight in self.edges:
for path, current_cost in paths[source].items():
new_cost = current_cost + weight
if path not in paths[destination] or
paths[destination][path] > new_cost:
paths[destination][path] = new_cost
updated = True

# Print the shortest paths


for vertex in range(self.vertices):
print(f"Shortest paths from vertex {start_vertex} to
{vertex}:")
for path, cost in paths[vertex].items():
print(f" Path via {path}, Cost: {cost}")

if __name__ == "__main__":
vertices = int(input("Enter the number of vertices: "))
edges = int(input("Enter the number of edges: "))
graph = Graph(vertices)

print("Enter the edges (source, destination, weight):")


for _ in range(edges):
source, destination, weight = map(int, input().split())
graph.add_edge(source, destination, weight)

start_vertex = int(input("Enter the starting vertex: "))


graph.path_pushing_algorithm(start_vertex)

Output:
EXPERIMENT 6

Objective: Implementation of Edge Chasing Algorithm

class Process:
def __init__(self, pid):
self.pid = pid
self.waiting_for = [] # Processes this process is waiting for

def add_dependency(self, process):


self.waiting_for.append(process)

def detect_deadlock(self, visited):


if self.pid in visited:
return True # Deadlock detected

visited.add(self.pid)

for process in self.waiting_for:


if process.detect_deadlock(visited):
return True

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:")
while True:
p1, p2 = map(int, input().split())
if p1 == -1 and p2 == -1:
break
processes[p1].add_dependency(processes[p2])

# Initiate deadlock detection


start_process = int(input("Enter the process initiating the probe: "))
if processes[start_process].detect_deadlock(set()):
print("Deadlock detected!")
else:
print("No deadlock detected.")

Output:
EXPERIMENT 7

Objective: Implementation of Commit Protocol Algorithm

class Participant:
def __init__(self, pid):
self.pid = pid
self.vote = None # 'commit' or 'abort'

def decide_vote(self):
import random
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")
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:
EXPERIMENT 8

Objective: Implementation of Voting Protocol Algorithm

class Participant:
def __init__(self, pid):
self.pid = pid
self.vote = None # 'yes' or 'no'

def cast_vote(self):
import random
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:
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:

You might also like