0% found this document useful (0 votes)
1 views40 pages

DS Practical File

The document outlines a B.Tech lab file for Distributed Systems, including various programming assignments related to distributed computing concepts such as Lamport's Logical Clock, Vector Clocks, and Distributed Mutual Exclusion. Each program is detailed with its aim, code snippets, and explanations of algorithms implemented in C and Java. The document serves as a practical guide for students to understand and simulate distributed systems functionalities.

Uploaded by

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

DS Practical File

The document outlines a B.Tech lab file for Distributed Systems, including various programming assignments related to distributed computing concepts such as Lamport's Logical Clock, Vector Clocks, and Distributed Mutual Exclusion. Each program is detailed with its aim, code snippets, and explanations of algorithms implemented in C and Java. The document serves as a practical guide for students to understand and simulate distributed systems functionalities.

Uploaded by

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

DISTRIBUTED

SYSTEMS LAB FILE


B.Tech
Semester- VII
SUB CODE: KCS 751

Session:2024-25

Submitted to: Submitted by:


Prof. Ankita Sharma. Praanjal Raikwar
Branch - CSE

1
Roll no: 2102300100116

INDEX

Sn Name Of Program Page No. Remarks


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

WAP to Implement Vector clock in C.


2 7

Simulation of Distributed mutual


3 exclusion in java. 10

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

Implementation of Path Pushing


5 Algorithm 23

Implementation of Edge Chasing


6 Algorithm 31

Implementation of Commit Protocol


7 Algorithm 34

2
Implementation of Voting Protocol
8 Algorithm 37

3
Program No.1
AIM: WAP to simulate the functionality of Lamport's Logical clock in C.
#include<stdio.h>

#include<conio.h>

#include<iostream.h>

#include<stdlib.h>

#include<graphics.h>

#include<string.h>

#include<dos.h>

void main(){

int s[4][9],n,m=0; int


i,j,next=0,step=0;

int msg[10][4]={0},totmsg;
char op;

int pi,pj,ei,ej;

clrscr();

cout<<"\nProgram for Lamport Logical Clock"; cout<<"\


nEnter Number Of Process ";

cin>>n;

for(i=0;i<n;i++){

cout<<"\nEnter number of STATES of process P"<<i<<" ";

cin>>s[i][8];

for(j=1;j<=s[i][8];j++){ s[i]

[j]=j;

do{

cout<<"\nEnter message transit"; cout<<"\nFROM

->\nEnter Process Number P"; cin>>msg[m][0];

cout<<"\nEnter Event Number e";

4
cin>>msg[m][1];

cout<<"\nTO ->\nEnter Process Number P"; cin>>msg[m][2];

cout<<"\nEnter Event Number e";

cin>>msg[m][3]; cout<<"\n\nPress

'y' to continue"; op=getch() }

cout<<op;

m++;

totmsg=m;

}while(op=='y');
m=0;

for (i=0;i<totmsg;i++)

{ pi=msg[i][0];

ei=msg[i][1];

pj=msg[i][2];

ej=msg[i][3];

if(s[pj][ej]< (s[pi][ei]+1))
{ s[pj][ej]=s[pi][ei]+1;

for (j=ej+1;j<=s[pj][8];j++){

s[pj][j]=s[pj][j-1]+1;

int gd=DETECT,gm; initgraph(&gd,&gm,"C:\\TC\\


BGI");

outtextxy(200,15,"Program For Lamport Logical Clock");

//drawing process and events

for(i=0;i<n;i++){

char* p1;

itoa(i,p1,10);

outtextxy(5,100+next,"P");

5
outtextxy(13,100+next,p1);

line(100,100+next,600,100+next); for(j=1;j<=s[i]

[8];j++){

char* p2;
itoa(j,p2,10);

outtextxy(100+step,90+next,"e");

outtextxy(110+step,90+next,p2);

//timestamp

char* p3;

itoa(s[i][j]-1,p3,10);

outtextxy(100+step,110+next,"t");

outtextxy(110+step,110+next,p3);

circle(105+step,100+next,5);

step+=50;

step=0;

next+=100;

delay(2000);

//drawing message transit

for(m=0;m<totmsg;m++)

{ setlinestyle(SOLID_LINE,1,3);

setcolor(m+4);

line(msg[m][1]*50+50,msg[m][0]*100+100,msg[m][3]*50+50,msg[m][2]*100+100);

if (msg[m][2]>msg[m][0]){ line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m]

[3]*50+50,msg[m][2]*100+90);

line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m][2]*100+90);

else{ line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+50,msg[m]

[2]*100+110); line(msg[m][3]*50+50,msg[m][2]*100+100,msg[m][3]*50+40,msg[m]

[2]*100+110);

}}

6
getch(); }

7
Program No.2
AIM: WAP to Implement Vector clock in C.
#include<stdio.h>

#include<conio.h>

#include<stdio.h>

#include<stdlib.h>

long *p1(int i,long *comp);

long *p2(int i,long *comp);

long *p3(int i,long *comp);

void main()

long start[]={0,0,0},*vector;
clrscr();

while(!kbhit())

p1(1,&start[0]);

printf("\n Process Vector\n");

vector=p1(0,&start[0]);

printf("p1[%ld%ld%ld]\n",*vector,*(vector+1),*(vector+2));

vector=p2(0,&start[0]); printf("p2[%ld%ld%ld]\

n",*vector,*(vector+1),*(vector+2)); vector=p3(0,&start[0]);

printf("p3[%ld%ld%ld]\n",*vector,*(vector+1),*(vector+2));

long *p1(int i,long *comp)

static long a[]={0,0,0};


int next;

if(i==1)

8
a[0]++;

if(*(comp+1)>a[1])

a[1]=*(comp+1);

if(*(comp+2)>a[2])

a[2]=*(comp+2);

next=random(2);

if(next==0)

p2(1,&a[0]);

else if(next==1)
p3(1,&a[0]);

return(&a[0]);

else

return(&a[0]);

long *p2(int i,long *comp)

{ static long b[]={0,0,0};

int next;
if(i==1) {

b[i]++;

if(*comp>b[0])

b[0]=*(comp);

if(*(comp+2)>b[2])

b[2]=*(comp+2);

next=random(2);

if(next==0)

p1(1,&b[0]);

else if(next==1)

p3(1,&b[0]);

return &b[0];

else

9
return &b[0];

long *p3(int i,long *comp)

{ static long c[]={0,0,0};

int next;

if(i==1) {

c[2]++;

if(*comp>c[0])

c[0]=*(comp);

if(*(comp+1)>c[1])

c[1]=*(comp+1);

next=random(2);

if(next==0)

p1(1,&c[0]);

return &c[0];

else

return &c[0];

1
0
Program No.3
AIM: Simulation of Distributed mutual exclusion in java.
import Utilities.*;

import Synchronization.*;

class Message { public int number, id;

public Message(int number, int id) { this.number = number; this.id = id;}

class Node extends MyObject implements Runnable { private

static final int MAIN = 0, REQUESTS = 1, REPLIES = 2; private

int whichOne = 0;

private int id = -1;

private int numNodes = -1;

private int napOutsideCS = 0; // both are in

private int napInsideCS = 0; // milliseconds private

MessagePassing[] requestChannel = null; private

MessagePassing[] replyChannel = null; private

MessagePassing requestsToMe = null; private

MessagePassing repliesToMe = null; private int

number = 0;

private int highNumber = 0; private

boolean requesting = false; private

int replyCount = 0;

private BinarySemaphore s = new BinarySemaphore(1); private

BinarySemaphore wakeUp = new BinarySemaphore(0); private

boolean[] deferred = null;

public Node(String name, int id, int numNodes, int


napOutsideCS, int napInsideCS,

MessagePassing[] requestChannel, MessagePassing replyChannel[],

MessagePassing requestsToMe, MessagePassing repliesToMe) { super(name +

" " + id);

this.id = id;

10
this.numNodes = numNodes;

this.napOutsideCS = napOutsideCS;

this.napInsideCS = napInsideCS;

this.requestChannel = requestChannel;

this.replyChannel = replyChannel;

this.requestsToMe = requestsToMe;

this.repliesToMe = repliesToMe; deferred

= new boolean[numNodes];

for (int i = 0; i < numNodes; i++) deferred[i] = false;


System.out.println(getName() + " is alive, napOutsideCS="

+ napOutsideCS + ", napInsideCS=" + napInsideCS); new


Thread(this).start();

public void run() { // start three different threads in the same object int

meDo = whichOne++;

if (meDo == MAIN) { new

Thread(this).start();

main();

} else if (meDo == REQUESTS)

{ new Thread(this).start();

handleRequests();

} else if (meDo == REPLIES)


{ handleReplies();
}

private void chooseNumber()

{ P(s);

requesting = true;

number = highNumber + 1;
V(s);

private void sendRequest() {

11
replyCount = 0;

for (int j = 0; j < numNodes; j++) if (j != id)


send(requestChannel[j], new Message(number, id));

private void waitForReply()

{ P(wakeUp);

private void replyToDeferredNodes()

{ P(s);

requesting = false;

V(s);

for (int j = 0; j < numNodes; j++)

{ if (deferred[j]) {

deferred[j] = false;

send(replyChannel[j], id);

}
}

private void outsideCS()

{ int napping;

napping = ((int) random(napOutsideCS)) + 1;

System.out.println("age()=" + age() + ", " + getName()

+ " napping outside CS for " + napping + " ms");

nap(napping);

private void insideCS()

{ int napping;

napping = ((int) random(napInsideCS)) + 1;

System.out.println("age()=" + age() + ", " + getName()

+ " napping inside CS for " + napping + " ms"); nap(napping);

12
private void main()

{ while (true)

{ outsideCS();

System.out.println("age()=" + age() + ", node " + id

+ " wants to enter its critical section");

chooseNumber(); // PRE-PROTOCOL

sendRequest(); // "

waitForReply(); // "

insideCS();

System.out.println("age()=" + age() + ", node " + id

+ " has now left its critical section");


replyToDeferredNodes(); // POST-PROTOCOL

private void handleRequests()


{ while (true) {

Message m = (Message) receive(requestsToMe);

int receivedNumber = m.number;

int receivedID = m.id;

highNumber = Math.max(highNumber, receivedNumber);

P(s);

boolean decideToDefer = requesting && (number < receivedNumber

|| (number == receivedNumber && id < receivedID)); if

(decideToDefer) deferred[receivedID] = true;

else send(replyChannel[receivedID], id);


V(s);

private void handleReplies()


{ while (true) {

int receivedID = receiveInt(repliesToMe);

replyCount++;

13
if (replyCount == numNodes - 1) V(wakeUp);

class DistributedMutualExclusion extends MyObject

{ public static void main(String[] args) {

// parse command line options, if any, to override defaults

GetOpt go = new GetOpt(args, "Un:R:");

String usage = "Usage: -n numNodes -R runTime"

+ " napOutsideCS[i] napInsideCS[i] i=0,1,...";

go.optErr = true;

int ch = -1;

int numNodes = 5;

int runTime = 60; // seconds

while ((ch = go.getopt()) != go.optEOF)


{ if ((char)ch == 'U') {

System.out.println(usage); System.exit(0);

else if ((char)ch == 'n')

numNodes = go.processArg(go.optArgGet(), numNodes);

else if ((char)ch == 'R')

runTime = go.processArg(go.optArgGet(), runTime);


else {

System.err.println(usage); System.exit(1);

System.out.println("DistributedMutualExclusion: numNodes="

+ numNodes + ", runTime=" + runTime)

// process non-option command line arguments


int[] napOutsideCS = new int[numNodes];

int[] napInsideCS = new int[numNodes]; int

argNum = go.optIndexGet();

14
for (int i = 0; i < numNodes; i++) { napOutsideCS[i]

= go.tryArg(argNum++, 8); napInsideCS[i] =

go.tryArg(argNum++, 2);

// create communication channels

MessagePassing[] requestChannel = null, replyChannel = null,

requestChannelS = null, requestChannelR = null, replyChannelS =

null, replyChannelR = null;

requestChannel = new MessagePassing[numNodes];

replyChannel = new MessagePassing[numNodes];

requestChannelS = new MessagePassing[numNodes];

replyChannelS = new MessagePassing[numNodes];

requestChannelR = new MessagePassing[numNodes];

replyChannelR = new MessagePassing[numNodes]; for

(int i = 0; i < numNodes; i++) {

requestChannel[i] = new AsyncMessagePassing();

replyChannel[i] = new AsyncMessagePassing();

requestChannelS[i] = new MessagePassingSendOnly(requestChannel[i]);

replyChannelS[i] = new MessagePassingSendOnly(replyChannel[i]);

requestChannelR[i] = new MessagePassingReceiveOnly(requestChannel[i]);

replyChannelR[i] = new MessagePassingReceiveOnly(replyChannel[i]);

// create the Nodes (they start their own threads)

for (int i = 0; i < numNodes; i++)

new Node("Node", i, numNodes,

napOutsideCS[i]*1000, napInsideCS[i]*1000,

requestChannelS, replyChannelS,

requestChannelR[i], replyChannelR[i]);

System.out.println("All Nodes created");

// let the Nodes run for a while

nap(runTime*1000);

System.out.println("age()=" + age()

15
+ ", time to stop the threads and exit");

System.exit(0);

Output:
D:\Prakash\Java\RND\Advanced>javac dimu.java

D:\ Prakash\Java\RND\Advanced >java DistributedMutualExclusion -R20

DistributedMutualExclusion: numNodes=5, runTime=20

Node 0 is alive, napOutsideCS=8000, napInsideCS=2000

Node 1 is alive, napOutsideCS=8000, napInsideCS=2000

Node 2 is alive, napOutsideCS=8000, napInsideCS=2000

Node 3 is alive, napOutsideCS=8000, napInsideCS=2000

Node 4 is alive, napOutsideCS=8000, napInsideCS=2000

age()=170, Node 1 napping outside CS for 2719 ms

age()=170, Node 2 napping outside CS for 279 ms

All Nodes created

age()=170, Node 3 napping outside CS for 2355 ms

age()=220, Node 0 napping outside CS for 2393 ms

age()=220, Node 4 napping outside CS for 8 ms

age()=220, node 4 wants to enter its critical section

age()=330, Node 4 napping inside CS for 911 ms

age()=440, node 2 wants to enter its critical section

age()=1260, node 4 has now left its critical section

age()=1260, Node 4 napping outside CS for 4042 ms

age()=1260, Node 2 napping inside CS for 183 ms

age()=1480, node 2 has now left its critical section

age()=1480, Node 2 napping outside CS for 7335 ms

age()=2530, node 3 wants to enter its critical section

age()=2530, Node 3 napping inside CS for 741 ms

age()=2580, node 0 wants to enter its critical section

age()=2860, node 1 wants to enter its critical section

16
age()=3300, node 3 has now left its critical section

age()=3300, Node 3 napping outside CS for 6849 ms

age()=3300, Node 0 napping inside CS for 1710 ms

age()=5000, node 0 has now left its critical section

age()=5000, Node 0 napping outside CS for 5253 ms

age()=5000, Node 1 napping inside CS for 1694 ms

age()=5330, node 4 wants to enter its critical section

age()=6700, node 1 has now left its critical section

age()=6700, Node 1 napping outside CS for 3063 ms

age()=6700, Node 4 napping inside CS for 397 ms

age()=7140, node 4 has now left its critical section

age()=7140, Node 4 napping outside CS for 3687 ms

age()=8790, node 2 wants to enter its critical section

age()=8790, Node 2 napping inside CS for 102 ms

age()=8900, node 2 has now left its critical section.

age()=8900, Node 2 napping outside CS for 1174 ms

age()=9780, node 1 wants to enter its critical section

age()=9780, Node 1 napping inside CS for 1617 ms

age()=10110, node 2 wants to enter its critical section

age()=10160, node 3 wants to enter its critical section

age()=10270, node 0 wants to enter its critical section

age()=10820, node 4 wants to enter its critical section

age()=11430, node 1 has now left its critical section

age()=11430, Node 1 napping outside CS for 5326 ms

age()=11430, Node 2 napping inside CS for 628 ms

age()=12090, node 2 has now left its critical section

age()=12090, Node 2 napping outside CS for 4970 ms

age()=12090, Node 3 napping inside CS for 545 ms

age()=12630, node 3 has now left its critical section

age()=12630, Node 3 napping outside CS for 7989 ms

age()=12630, Node 0 napping inside CS for 904 ms

age()=13510, node 0 has now left its critical section

17
age()=13510, Node 0 napping outside CS for 4162 ms

age()=13510, Node 4 napping inside CS for 1440 ms

age()=15000, node 4 has now left its critical section

age()=15000, Node 4 napping outside CS for 2578 ms

age()=16750, node 1 wants to enter its critical section

age()=16750, Node 1 napping inside CS for 123 ms

age()=16860, node 1 has now left its critical section

age()=16860, Node 1 napping outside CS for 3709 ms

age()=17030, node 2 wants to enter its critical section

age()=17030, Node 2 napping inside CS for 97 ms

age()=17140, node 2 has now left its critical section

age()=17140, Node 2 napping outside CS for 7901 ms

age()=17580, node 4 wants to enter its critical section

age()=17580, Node 4 napping inside CS for 1695 ms

age()=17690, node 0 wants to enter its critical section

age()=19280, node 4 has now left its critical section

age()=19280, Node 4 napping outside CS for 3751 ms

age()=19280, Node 0 napping inside CS for 869 ms

age()=20160, node 0 has now left its critical section

age()=20160, Node 0 napping outside CS for 6489 ms

age()=20160, time to stop the threads and exit

... end of example run(s) */

18
Program No.4
AIM: Implementation of CORBA (Common Object Request Broker
Architecture) mechanism.
1.FileInterface.idl
interface FileInterface {

typedef sequence<octet> Data;

Data downloadFile(in string fileName);

};

Now, let's compile the FileInterface.idl and generate server-side skeletons. Using the
command:

D:\Prakash\RND\Java\CORBA> idlj -fserver FileInterface.idl


2.FileServant.java

import java.io.*;

public class FileServant extends _FileInterfaceImplBase

{ public byte[] downloadFile(String fileName){

File file = new File(fileName);

byte buffer[] = new byte[(int)file.length()]; try

BufferedInputStream input = new

BufferedInputStream(new FileInputStream(fileName));

input.read(buffer,0,buffer.length);

input.close();

} catch(Exception e) {

System.out.println("FileServant Error: "+e.getMessage());

e.printStackTrace();

return(buffer);

3.FileServer.java

import java.io.*;

19
import org.omg.CosNaming.*;

import org.omg.CosNaming.NamingContextPackage.*;

import org.omg.CORBA.*;

public class FileServer {

public static void main(String args[])

{ try{

// create and initialize the ORB

ORB orb = ORB.init(args, null);

// create the servant and register it with the ORB

FileServant fileRef = new FileServant(); orb.connect(fileRef);

// get the root naming context

org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService");

NamingContext ncRef = NamingContextHelper.narrow(objRef);

// Bind the object reference in naming

NameComponent nc = new NameComponent("FileTransfer", " ");


NameComponent path[] = {nc};

ncRef.rebind(path, fileRef);

System.out.println("Server started ");

// Wait for invocations from clients

java.lang.Object sync = new java.lang.Object();

synchronized(sync){

sync.wait();

} catch(Exception e) { System.err.println("ERROR:

" + e.getMessage());

e.printStackTrace(System.out);

20
4.FileClient.java

import java.io.*;

import java.util.*;

import org.omg.CosNaming.*;

import org.omg.CORBA.*;

public class FileClient {

public static void main(String argv[])

{ try {

// create and initialize the ORB


ORB orb = ORB.init(argv, null);

// get the root naming context

org.omg.CORBA.Object objRef =

orb.resolve_initial_references("NameService");

NamingContext ncRef = NamingContextHelper.narrow(objRef);

NameComponent nc = new NameComponent("FileTransfer", " ");

// Resolve the object reference in naming

NameComponent path[] = {nc};

FileInterfaceOperations fileRef =

FileInterfaceHelper.narrow(ncRef.resolve(path));

if(argv.length < 1) {

System.out.println("Usage: java FileClient filename");

// save the file

File file = new File(argv[0]);

byte data[] = fileRef.downloadFile(argv[0]);

BufferedOutputStream output = new

BufferedOutputStream(new FileOutputStream(argv[0]));

output.write(data, 0, data.length);

output.flush();
output.close();
} catch(Exception e) {

System.out.println("FileClient Error: " + e.getMessage());

21
e.printStackTrace();

Running the application

1. D:\Prakash\RND\Java\CORBA>tnameserv

2. D:\Prakash\RND\Java\CORBA>java FileServer

3. D:\Prakash\RND\Java\CORBA>idlj -fclient FileInterface.idl

4. D:\Prakash\RND\Java\CORBA>java FileClient hello.txt

Output:

22
Program No.5
AIM: Implementation of Path Pushing Algorithm
#include<stdio.h>

#include<stdlib.h>

#include<iostream>

#include<math.h>

#include<time.h>

using namespace std;

//Variable for number of printers,fax,scanner and tapedrive int


no_printer,no_fax,no_scanner,no_tapedrive;

//Used for calculating the random assignment of resources

int sum=0,sum1=0,sum2=0,sum3=0;

//Variable for number of printers,fax,scanner and tapedrive on hold by users int


r1,r2,r3,r4;

//fraction[]->It is used for randomly storing the number of resources allocated at any time int

fraction[4];

int fraction1[4];

int fraction2[4];

int fraction3[4];

//request[]->It is used for storing the resources requested by users at any time.
int request[4];

int request1[4];

int request2[4];

int request3[4];

/*available[]->It is used to check for the resources available by substracting the total number of
resources available
with total number of resources on hold.*/

int available[4];
void Calculate();

23
int main()

cout<<" Welcome to office resources usage software developed by Cppsecrets


"<<endl;

cout<<" "<<endl;

cout<<" "<<endl;

cout<<"Enter the number of printers your company has"<<endl;


cin>>no_printer;

cout<<"Enter the number of fax your company has"<<endl;

cin>>no_fax;

cout<<"Enter the number of scanner your company has"<<endl;

cin>>no_scanner;

cout<<"Enter the number of tapedrive your company has"<<endl;

cin>>no_tapedrive;

cout<<"Enter the printer,fax,scanner,tapedrive requirements for Kumar ";

for(int i=0;i<4;i++)

{
cin>>request[i];

cout<<"Enter the printer,fax,scanner,tapedrive requirements for Harsh ";

for(int i=0;i<4;i++)

cin>>request1[i];

cout<<"Enter the printer,fax,scanner,tapedrive requirements for Vipul "; for(int

i=0;i<4;i++)

cin>>request2[i];

cout<<"Enter the printer,fax,scanner,tapedrive requirements for Ramesh ";


for(int i=0;i<4;i++)

24
{

cin>>request3[i];

/*srand(time0)-It used for generating a seed at a particular time otherwise if we use rand() in c+
+ directly
then it will always return the same random numbers after executing multiple times.

So by using srand() we will be generating random numbers.*/

srand(time(0));

int randnum[4];

int randnum1[4];

int randnum2[4];

int randnum3[4];

//for loop Used for generating random numbers within the max limit for

(int i = 0; i < 4; i++)

randnum[i]=((double) rand() / (RAND_MAX))*no_printer;

randnum1[i]=((double) rand() / (RAND_MAX))*no_fax;

randnum2[i]=((double) rand() / (RAND_MAX))*no_scanner;

randnum3[i]=((double) rand() / (RAND_MAX))*no_tapedrive;

sum+=randnum[i];

sum1+=randnum1[i];

sum2+=randnum2[i];

sum3+=randnum3[i];

//for loop used for random distribution of resources for

(int i = 0; i < 4; i++)

fraction[i]=(no_printer*randnum[i]/sum);
fraction1[i]=(no_fax*randnum1[i]/sum1);

25
fraction2[i]=(no_scanner*randnum2[i]/sum2);

fraction3[i]=(no_tapedrive*randnum3[i]/sum3);

cout<<"\n\n ********** Displaying Total Resource Details ********** \n"<<" ";


cout<<"\n "<<"Printer"<<" "<<"Fax"<<" "<<"Scanner"<<" "<<"Tapedrive";

cout<<"\n "<<no_printer<<" "<<no_fax<<" "<<no_scanner<<"


"<<no_tapedrive;
cout<<"\n "<<"**********************************************************\n\
n"<<" ";

cout<<"\n\n ********** Displaying Resource on hold by employee Details **********


\n\n"<<" ";

cout<<"\n Employee id"<<" "<<"Name"<<" "<<"Printer"<<" "<<"Fax"<<"


"<<"Scanner"<<" "<<"Tapedrive";

cout<<"\n "<<1<<" "<<"Kumar"<<" "<<fraction[0]<<"


"<<fraction1[0]<<" "<<fraction2[0]<<" "<<fraction3[0];
cout<<"\n "<<2<<" "<<"Harsh"<<" "<<fraction[1]<<"
"<<fraction1[1]<<" "<<fraction2[1]<<" "<<fraction3[1];

cout<<"\n "<<3<<" "<<"Vipul"<<" "<<fraction[2]<<"


"<<fraction1[2]<<" "<<fraction2[2]<<" "<<fraction3[2];

cout<<"\n "<<4<<" "<<"Ramesh"<<" "<<fraction[3]<<"


"<<fraction1[3]<<" "<<fraction2[3]<<" "<<fraction3[3];
cout<<"\n "<<"**********************************************************\n\
n"<<" ";

r1=fraction[0]+fraction[1]+fraction[2]+fraction[3];

r2=fraction1[0]+fraction1[1]+fraction1[2]+fraction1[3];

r3=fraction2[0]+fraction2[1]+fraction2[2]+fraction2[3];

r4=fraction3[0]+fraction3[1]+fraction3[2]+fraction3[3];

cout<<"\n "<<"**********************************************************\n\
n"<<" ";

cout<<"\n\n ********** Displaying Total Resource on hold Details ********** \n"<<" ";

cout<<"\n "<<"Printer"<<" "<<"Fax"<<" "<<"Scanner"<<" "<<"Tapedrive";

cout<<"\n "<<r1<<" "<<r2<<" "<<r3<<" "<<r4;

cout<<"\n "<<"**********************************************************\n\
n"<<" ";

26
cout<<"\n\n ********** Displaying Total Resources available ********** \n"<<" ";

cout<<"\n "<<"Printer"<<" "<<"Fax"<<" "<<"Scanner"<<" "<<"Tapedrive";

cout<<"\n "<<no_printer-r1<<" "<<no_fax-r2<<" "<<no_scanner-r3<<"


"<<no_tapedrive-r4;
cout<<"\n "<<"**********************************************************\n\
n"<<" ";

cout<<"\n\n ********** Displaying Resource required by employee Details **********


\n\n"<<" ";

cout<<"\n Employee id"<<" "<<"Name"<<" "<<"Printer"<<" "<<"Fax"<<"


"<<"Scanner"<<" "<<"Tapedrive";

cout<<"\n "<<1<<" "<<"Kumar"<<" "<<request[0]<<"


"<<request[1]<<" "<<request[2]<<" "<<request[3];
cout<<"\n "<<2<<" "<<"Harsh"<<" "<<request1[0]<<"
"<<request1[1]<<" "<<request1[2]<<" "<<request1[3];

cout<<"\n "<<3<<" "<<"Vipul"<<" "<<request2[0]<<"


"<<request2[1]<<" "<<request2[2]<<" "<<request3[3];
cout<<"\n "<<4<<" "<<"Ramesh"<<" "<<request3[0]<<"
"<<request3[1]<<" "<<request3[2]<<" "<<request3[3];

cout<<"\n "<<"**********************************************************\n\
n"<<" ";

available[0]=no_printer-r1;

available[1]=no_fax-r2;

available[2]=no_scanner-r3;

available[3]=no_tapedrive-r4;

Calculate();

return 0;

}
/* We calculate the resources available and take the resources requested by users as input and
check for possibility of assigning the resources by taking counters if the resources requested by
a particular person is less

i.e. the number of printers,scanners,tapedrive,fax then the counter value is increased till 4.

If the counter value turns out to be 4 then

resources are assigned to the person and the total resources available at that time is

added upon by the persons resources in the available matrix.

If the counter does not go upto 4 in any case then deadlock is detected.*/

27
void Calculate()

int c1,c2,c3,c4;

c1=0,c2=0,c3=0,c4=0;

do

c1=0,c2=0,c3=0,c4=0;

for(int i=0;i<4;i++)

if(request[i]<=available[i])
c1+=1;

else

c1=-1;

if(c1==4)

for(int i=0;i<4;i++)

available[i]+=request[i];

for(int i=0;i<4;i++)

if(request1[i]<=available[i])
c2+=1;

else

c2=-1;

if(c2==4)

for(int i=0;i<4;i++)

28
available[i]+=request1[i];

for(int i=0;i<4;i++)

if(request2[i]<=available[i])

c3+=1;

else

c3=-1;

if(c3==4)

for(int i=0;i<4;i++)

available[i]+=request2[i];

for(int i=0;i<4;i++)

if(request3[i]<=available[i])

c4+=1;

else

c4=-1;

if(c4==4)

for(int i=0;i<4;i++)

available[i]+=request3[i];

29
if(c1!=4 && c2!=4 && c3!=4 && c4!=4)

cout<<"The system is in deadlock state";

break;

else{

cout<<"The system is not in deadlock";

break;

}while(c1==4||c2==4||c3==4||c4==4);

30
Program No.6
AIM: Implementation of Edge Chasing Algorithm

Implementation:
if Pi is locally dependent on itself then declare a deadlock else for all Pj and Pk such that

1 Pi is locally dependent upon Pj , and

2 Pj is waiting on Pk , and

3 Pj and Pk are on different sites,send a probe (i, j, k) to the home site of Pk

On the receipt of a probe (i, j, k), the site takes the following actions:

if

1 Pk is blocked, and

2 dependentk (i) is false, and

3 Pk has not replied to all requests Pj


then

begin

dependent k (i) = true;

if k=i

then declare that Pi is deadlocked


else for all Pm and Pn such that

(a’) Pk is locally dependent upon Pm, and


(b’) Pm is waiting on Pn, and

(c’) Pm and Pn are on different sites, send a probe (i, m, n) to the home site of Pn end.

A probe message is continuously circulated along the edges of the global TWF graph and a deadlock is
detected when a probe message returns to its initiating process.
One probe message (per deadlock detection initiation) is sent on every edge of the WFG which that two
sites. Thus, the algorithm exchanges at most m(n − 1)/2 messages to detect a deadlock that involves m
processes and that spans over n sites. The size of messages is fixed and is very small (only 3 integer
words). Delay in detecting a deadlock is O(n).

31
Program :

#include <stdio.h>
#define MAX_SITES 10

int main() {

int processes[MAX_SITES], n, i, p1, s1, sp1, sp2;

printf("Enter total number of sites: ");

scanf("%d", &n);

for (i = 0; i < n; i++) {

printf("Enter total number of processes in S%d: ", i + 1);

scanf("%d", &processes[i]);

printf("Deadlock Detection\n");

printf("Enter the site number and process ID for which deadlock detection should be initiated: ");

scanf("%d %d", &s1, &p1);

printf("Enter the processes of two different sites connected with requesting edge: ");
scanf("%d %d", &sp1, &sp2);

printf("Probe message is (%d, %d, %d)\n", p1, sp1, sp2);

if (p1 == sp2) {

printf("Deadlock detected\n");

} else {

printf("No deadlock detected\n");

32
return 0;

OUTPUT:
Enter total number of sites: 3

Enter total number of processes in S1: 4

Enter total number of processes in S2: 3

Enter total number of processes in S3: 5

Deadlock Detection

Enter the site number and process ID for which deadlock detection should be initiated: 2 3
Enter the processes of two different sites connected with requesting edge: 3 4

Probe message is (3, 3, 4)

Deadlock detected

33
Program No.7
AIM: Implementation of Commit Protocol Algorithm
#include <iostream>

#include <vector>

#include <algorithm>

enum class State

{ INIT,

READY,

COMMITTED,

ABORTED

};

class Node

{ private:

State state;

public:

Node() : state(State::INIT) {}

State getState() const

{ return state;

void setState(State newState)

{ state = newState;

};

class Coordinator

{ private:

34
std::vector<Node> nodes;

public:

Coordinator(int numNodes) : nodes(numNodes) {}

void beginTransaction() {

for (auto& node : nodes)

{ node.setState(State::READY);

void commitTransaction() {

bool allReady = std::all_of(nodes.begin(), nodes.end(), [](const Node& n) { return

n.getState() == State::READY;

});

if (allReady) {

for (auto& node : nodes)


{ node.setState(State::COMMITTED);

std::cout << "Transaction committed successfully!" << std::endl;

} else {

abortTransaction();

void abortTransaction() {

for (auto& node : nodes)

{ node.setState(State::ABORTED);

std::cout << "Transaction aborted!" << std::endl;

35
};

int main() {

// Create a coordinator with 3 nodes


Coordinator coordinator(3);

// Simulate a transaction

coordinator.beginTransaction();

// Commit or abort the transaction

coordinator.commitTransaction();

return 0;

Output:
Transaction committed successfully!

36
Program No.7
AIM: Implementation of Voting Protocol Algorithm

#include <iostream>

#include <vector>

#include <algorithm>

enum class Vote


{ YES,

NO,

UNDECIDED

};

class Node

{ private:

Vote vote;

public:

Node() : vote(Vote::UNDECIDED) {}

void setVote(Vote v) {

vote = v;

Vote getVote() const {

return vote;

};

class VotingProtocol

{ private:

37
std::vector<Node> nodes;

public:

VotingProtocol(int numNodes) : nodes(numNodes) {}

void startVoting() {

// Simulating nodes casting votes

for (auto& node : nodes) {

if (rand() % 2 == 0)
{ node.setVote(Vote::YES);

} else {

node.setVote(Vote::NO);

void countVotes() {

int yesCount = 0;

int noCount = 0;

for (const auto& node : nodes) {

if (node.getVote() == Vote::YES)
{ yesCount++;

} else if (node.getVote() == Vote::NO)

{ noCount++;

if (yesCount > noCount) {

std::cout << "Consensus: Majority voted YES" << std::endl;

} else if (noCount > yesCount) {

std::cout << "Consensus: Majority voted NO" << std::endl;

38
} else {

std::cout << "Consensus: No majority, undecided" << std::endl;

};

int main() {

// Create a voting protocol with 5 nodes

VotingProtocol protocol(5);

// Start the voting process


protocol.startVoting();

// Count and decide based on votes

protocol.countVotes();

return 0;

OUTPUT:

39

You might also like