0% found this document useful (0 votes)
8 views26 pages

Arpit Chaudhary - DS - LAB - FILE

This document is a lab file for a Bachelor's program in Computer Science and Engineering, detailing various experiments related to distributed systems. It includes implementations of Lamport's Logical Clock, Vector Clock, Distributed Mutual Exclusion, CORBA, Path Pushing Algorithm, Edge Chasing Algorithm, and Commit Protocol Algorithm. Each experiment contains objectives, code implementations, and expected outputs.
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)
8 views26 pages

Arpit Chaudhary - DS - LAB - FILE

This document is a lab file for a Bachelor's program in Computer Science and Engineering, detailing various experiments related to distributed systems. It includes implementations of Lamport's Logical Clock, Vector Clock, Distributed Mutual Exclusion, CORBA, Path Pushing Algorithm, Edge Chasing Algorithm, and Commit Protocol Algorithm. Each experiment contains objectives, code implementations, and expected outputs.
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/ 26

Session: 2024-2025

Bachelors of Technology
In Computer Science and
Engineering

DISTRIBUTED SYSTEMS LAB FILE


(KCS751A)

Submitted to Submitted by

Ms. Ankita Sharma Arpit Chaudhary


Uni. Roll No. - 2102300100044
College Roll No. – 16039
4th year

Affiliated to DR. APJ ABDUL KALAM TECHNICAL UNIVERSITY


LUCKNOW

1
INDEX

Sno. Name Of Program Page No. Remarks

WAP to simulate the functionality of 3-5


1
Lamport's Logical clock in C.

WAP to Implement Vector clock in C.


2 6-9

Simulation of Distributed mutual


3 10-14
exclusion in java.

Implementation of CORBA (Common


4 15-17
Object Request Broker Architecture)
mechanism.

Implementation of Path Pushing


5 18-20
Algorithm

Implementation of Edge Chasing


6 20-22
Algorithm

Implementation of Commit Protocol


7 23-24
Algorithm

Implementation of Voting Protocol


8 25-26
Algorithm

2
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

// Function to return the maximum of two integers


int max(int a, int b) {
return (a > b) ? a : b;
}

// Function to calculate the Lamport Logical Clock


void lamport_logical_clock(int events[], int n) {
int logical_clock[MAX_EVENTS] = {0}; // Array to store logical clock
values

logical_clock[0] = 1; // The first event starts with timestamp 1

// Calculate the timestamp for each event


for (int i = 1; i < n; i++) {
logical_clock[i] = max(logical_clock[i - 1], events[i]) + 1;
}

// Print the logical clock timestamps


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

// Input the number of events


printf("Enter the number of events: ");
scanf("%d", &n);

// Validate the number of events


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;
}

4
Output:

5
EXPERIMENT 2

Objective: WAP to Implement Vector clock in C.


#include <stdio.h>
#define MAX 10

// Initialize the vector clock


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;
}

// Display the vector clock


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

// Handle an internal event


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

// Handle a message event


void message_event(int vc[MAX][MAX], int sender, int receiver, int n) {
vc[sender][sender]++;
for (int i = 0; i < n; i++) {
6
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);
if (n <= 0 || n > MAX) {
printf("Invalid number of processes!\n");
return 1;
}

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

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);
}

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

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

11
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;
}

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

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.*;
import org.omg.PortableServer.POA;
import org.omg.CosNaming.*;
import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;

public class HelloServer {


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

// Get reference to RootPOA and activate the POA Manager


POA rootPOA =
POAHelper.narrow(orb.resolve_initial_references("RootPOA"));
rootPOA.the_POAManager().activate();
15
// Create the servant and register it with the ORB
HelloServant helloServant = new HelloServant();
org.omg.CORBA.Object ref =
rootPOA.servant_to_reference(helloServant);
Hello helloRef = HelloHelper.narrow(ref);

// Get the Naming Service reference


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

// Bind the object reference in the Naming Service


String name = "Hello";
NameComponent[] path = ncRef.to_name(name);
ncRef.rebind(path, helloRef);

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

// Keep the server running


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

// Implementation of the Hello interface


class HelloServant extends HelloPOA {
@Override
public String sayHello() {
return "Hello from CORBA Server!";
}

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;

public class HelloClient {


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

// Get a reference to the Naming Service


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

// Resolve the object reference using the name "Hello"


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

// Call the method on the server and print the response


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

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

17
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

18
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)

19
Output:

20
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:")
21
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:

22
EXPERIMENT 7

Objective: Implementation of Commit Protocol Algorithm

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

Objective: Implementation of Voting Protocol Algorithm


import random

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

You might also like