DC 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Distributed Global Average

def time(s):
ans = s.split(":")
return int(ans[0]) * 60 + int(ans[1]) + int(ans[2])/60

n = input("Enter the agreed clock time: ")

init_val = time(n)

nodes = int(input("Enter the number of nodes: "))

dict_nodes = {}
ls = []

for i in range(nodes):
print(f"Enter the clock time for {i + 1} node : ")
x = input()
ls.append(time(x))
dict_nodes[chr(97 + i)] = []

print()
for key in dict_nodes.keys():
print(f"{key} : {dict_nodes[key]}")

print()
print(ls)

for i in range(nodes):
val = -float('inf')
for i in range(nodes):
diff = ls[i] - init_val
dict_nodes[chr(97 + i)].append(diff)
if diff < 0:
val = max(val, diff)
for i in range(nodes):
if val != -float('inf'):
ls[i] += abs(val)
print()
print(*ls)

print()
for key in dict_nodes.keys():
print(f"{key} : {dict_nodes[key]}")

for i in range(nodes):
avg = sum(dict_nodes[chr(97 + i)]) / nodes
if avg >= 0:
ls[i] -= abs(avg)
else:
ls[i] += abs(avg)
print()
print(ls)

def get_time(val):
hours = int(val // 60)
mins = int(val - hours * 60)
seconds = int((val - int(val)) * 60)
return str(hours) + ":" + str(mins) + ":" + str(seconds)

for i in range(nodes):
print(f'Time for Node {chr(97 + i)} : ', get_time(ls[i]))
Multithreading

class threads extends Thread


{
threads()
{
super("User Threads");
System.out.println("User thread is created" + this);
start();
}
public void run() {
try {
for (int i=0 ;i<8;i++) {
System.out.println("Printing the count of Child Thread" + i);
Thread.sleep(800);
}
}
catch(InterruptedException e) {
System.out.println("User thread interrupted");
}
System.out.println("Child thread run is over" );
}
}
class Multithreadings { public static
void main(String args[]) { threads th
= new threads();
try {
while(th.isAlive()) {
System.out.println("Parent thread will run till the Child thread is alive");
Thread.sleep(1500);
}
}
catch(InterruptedException e) {
System.out.println("Parent thread interrupted");
}
System.out.println("Parent thread's run is over" );
}
}
RicartAgrawala

numProcesses = int(input("Enter number of processes: "))


numCS = int(input("Enter Number of processes that want to enter CS: "))
# timestamp: process
processMap = {}
timestamps = []
for i in range(numCS):
process, timestamp = input(f"Enter the Process ID and Timestamp of process: ").split()
processMap[int(timestamp)] = int(process)
timestamps.append(int(timestamp))
print()
timestamps.sort()
for time in timestamps:
processCS = processMap[time]
for i in range(numProcesses):
if(processCS != i):
print(f"Process {processCS} has requested Process {i}")
print()
for time in timestamps:
processCS = processMap[time]
for i in range(numProcesses):
if(processCS != i):
print(
f"Process {i} has Accepted the request of process {processCS}")
print()
print(f'Process {processCS} has now entered the CS')
print(f'Process {processCS} has now exited the CS')
print()
Berkley Method

def time(s):
ans = s.split(":")
return int(ans[0]) * 60 + int(ans[1]) + int(ans[2])/60

slaves=int(input("Enter the number of clients : "))

master = input("Enter the Time of master node : ")


masterTime=time(master)
print(masterTime)

ls = []

for i in range(slaves):
print(f"Enter the clock time for slave {i + 1} : ")
x = input()
print(time(x))
ls.append(time(x))

def get_time(val):
hours = int(val // 60)
mins = int(val - hours * 60)
seconds = int((val - int(val)) * 60)
return str(hours) + ":" + str(mins) + ":" + str(seconds)

def berkeley_sync(master_time, client_times):


clients=[time-master_time for time in client_times]
print(clients)
avg_time = sum(clients) / (len(client_times)+1)
print(avg_time)

masterAdjustedTime=master_time+avg_time

adjusted_times = [masterAdjustedTime-time for time in client_times]

print(masterAdjustedTime)
print(get_time(masterAdjustedTime))

return adjusted_times,masterAdjustedTime

ans, masterAdjustedTime=berkeley_sync(masterTime,ls)
print(ans)
for i in range(slaves):
print(f"Time for slave {i+1} : {get_time(ls[i]+ans[i])}")

print(f"Time of master node : {get_time(masterAdjustedTime)}")


IPC

Server:

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
// Create a server socket listening on port 12345
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server is running...");

// Wait for client connection


Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");

// Create input and output streams for communication


BufferedReader in = new BufferedReader(newInputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

// Input stream reader for reading server terminal input


BufferedReader serverInput = new BufferedReader(new InputStreamReader(System.in));

// Start a separate thread for reading server terminal input and sending to client
new Thread(() -> {
try {
String serverMessage;
while ((serverMessage = serverInput.readLine()) != null) {
out.println("Server: " + serverMessage);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();

// Continuously read messages from client and echo them back


String message;
while ((message = in.readLine()) != null) {
System.out.println("process 2: " + message);
}
// Close streams and sockets
in.close();
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
Client:

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
// Connect to the server running on localhost, port 12345
Socket socket = new Socket("localhost", 12345);
System.out.println("Connected to server.");

// Create input and output streams for communication


BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

// Send messages to server and receive echoes


BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
String message;
while (true) {
System.out.print("Enter message to send to server (or type 'exit' to quit): ");
message = userInput.readLine();
if ("exit".equalsIgnoreCase(message)) {
break;
}
out.println(message);
System.out.println("process 1: " + in.readLine());
}

// Close streams and socket


in.close();
out.close();
userInput.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}}
Group Communication
Bully Algo

import java.util.Scanner;
class Pro {
int id;
boolean act;

Pro(int id) {
this.id = id;
this.act = true;
}
}
public class Bully {
int TotalProcess;
Pro[] process;

public static void main(String[] args) {


Bully object = new Bully();
Scanner scanner = new Scanner(System.in); System.out.print("Total number
of processes: ");
int numProcesses = scanner.nextInt(); object.initialize(numProcesses);
object.Election();
scanner.close();
}
public void initialize(int j) {
System.out.println("No of processes " + j);
this.TotalProcess = j;
this.process = new Pro[this.TotalProcess];
for (int i = 0; i < this.TotalProcess; i++) { this.process[i] = new Pro(i);
}
}
public void Election() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the process number to fail: ");
int process_to_fail = scanner.nextInt();

if (process_to_fail < 0 || process_to_fail >= this.TotalProcess) { System.out.println("Invalid


process number. Please enter a valid process number."); return;
}

System.out.println("Process no " + this.process[process_to_fail].id + " fails");


this.process[process_to_fail].act = false;
System.out.print("Enter the process initiating the election: ");
int initializedProcess = scanner.nextInt();
System.out.println("Election Initiated by " + initializedProcess);
int initBy = initializedProcess;

int i = -1;
for(i = initBy; i < TotalProcess - 1; i++){
if(this.process[i].act){
System.out.println("Process " + i + " passes Election(" + i + ")" + " to " +(i + 1));
}else{
System.out.println("Process " + (i-1) + " passes Election("
+ (i - 1) + ")" + " to " +(i + 1));
}
}
int coordinatorID = -1; if(this.process[i].act) {
coordinatorID = i;
}else{
coordinatorID = i - 1;
}
System.out.println("Process " + coordinatorID + " is the process with max ID");

for(int j = 0; j< coordinatorID; j++){


if(this.process[j].act)
System.out.println("Process " + coordinatorID + " passes Coordinator(" + coordinatorID + ") message
to process " + this.process[j].id);
}
scanner.close();
}
}
Raymond Tree algo

import java.util.ArrayList; import


java.util.LinkedList; import
java.util.List; import java.util.Queue;
import java.util.Scanner;

public class RaymondTree {


static List<Node> list = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = 8;
Node n1 = new Node(1, 1);
Node n2 = new Node(2, 1);
Node n3 = new Node(3, 1);
Node n4 = new Node(4, 2);
Node n5 = new Node(5, 2);
Node n6 = new Node(6, 3);
Node n7 = new Node(7, 3);
Node n8 = new Node(8, 3);
list.add(n1);
list.add(n2);
list.add(n3);
list.add(n4);
list.add(n5);
list.add(n6);
list.add(n7);
list.add(n8);

while (true) {
System.out.println("Enter the ID of the node requesting access to the
critical section (1-8), or 'exit' to quit:");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("exit")) {
break;
}
int nodeID;
try {
nodeID = Integer.parseInt(input);
if (nodeID < 1 || nodeID > 8) {
System.out.println("Invalid node ID. Please enter a number
between 1 and 8.");
continue;
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid node ID or
'exit'.");
continue;
}
List<Integer> req = new LinkedList<>();
req.add(nodeID);
System.out.println("Initially:");
printFunction();
for (int a : req) {
System.out.println("--------- Process " + a + " -----------");
request(a, a);
}
}
scanner.close();
}
private static void request(int holder, int req) {
Node n = list.get(holder - 1);
n.q.add(req);
System.out.println("Queue of " + n.id + ": " + n.q);
if (n.holder != n.id)
request(n.holder, n.id);
else
giveToken(n.id);
}
private static void giveToken(int nid) {
Node n = list.get(nid - 1);
int next = n.q.remove();
n.holder = next;
if (next != nid)
giveToken(next);
else
printFunction();
}
private static void printFunction() {
for (Node n : list) {
System.out.println("id: " + n.id + " Holder: " + n.holder);
}
}
}
class Node {
int id;
int holder;
Queue<Integer> q;

Node(int id, int holder) {


this.id = id;
this.holder = holder;
this.q = new LinkedList<>();
} }
Bankers

def main():
processes = int(input("number of processes : "))
resources = int(input("number of resources : "))
max_resources = [int(i) for i in input("maximum resources : ").split()]

print("\n-- allocated resources for each process --")


currently_allocated = [[int(i) for i in input(f"process {j + 1} : ").split()] for j in range(processes)]

print("\n-- maximum resources for each process --")


max_need = [[int(i) for i in input(f"process {j + 1} : ").split()] for j in range(processes)]

allocated = [0] * resources


for i in range(processes):
for j in range(resources):
allocated[j] += currently_allocated[i][j]
print(f"\ntotal allocated resources : {allocated}")

available = [max_resources[i] - allocated[i] for i in range(resources)]


print(f"total available resources : {available}\n")

sequence=[]

running = [True] * processes


count = processes
while count != 0:
safe = False
for i in range(processes):
if running[i]:
executing = True
for j in range(resources):
if max_need[i][j] - currently_allocated[i][j] > available[j]:
executing = False
break
if executing:
print(f"process {i + 1} is executing")
running[i] = False
count -= 1
safe = True
for j in range(resources):
available[j] += currently_allocated[i][j]
sequence.append(i+1)
break
if not safe:
print("the processes are in an unsafe state.")
break

print(f"the process is in a safe state.\navailable resources : {available}\n")

print("The sequence is :")


s=""
for i in range (processes-1):
s+=f"P{sequence[i]} -> "
s+=f"P{sequence[processes-1]}"

print(s)

if __name__ == '__main__':
main()
Load Balancing:

import java.util.Scanner;
class LoadBalancer{
static void printLoad(int servers,int Processes){
int each = Processes/servers;
int extra = Processes%servers;
int total = 0;
for(int i = 0; i < servers; i++){
if(extra-->0) total = each+1;
else total = each;
System.out.println("Server "+(char)('A'+i)+" has "+total+" Processes");
} }
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of servers and Processes: ");
int servers = sc.nextInt();
int Processes = sc.nextInt();
while(true){ printLoad(servers, Processes);
System.out.print("1.Add Servers 2.Remove Servers 3.Add Processes 4.Remove Processes 5.Exit: ");
switch(sc.nextInt()){
case 1:
System.out.print("How many more servers?: "); servers+=sc.nextInt();
break;
case 2:
System.out.print("How many servers to remove?: "); servers-=sc.nextInt();
break;
case 3:
System.out.print("How many more Processes?: ");

Processes+=sc.nextInt();
break;
case 4:
System.out.print("How many Processes to remove?: ");

Processes-=sc.nextInt();
break;
case 5: return;
}
}
}
}

You might also like