├── RPC and RMI Implementation.pdf ├── Election Algorithm - Bully and Ring ├── Distributed System Election Algorithm.docx ├── Election Algorithm Distributed System.pdf ├── bully_ring_election_algorithm.py └── bully_and_ring_election_algorithm.cpp ├── RMI Java ├── FactorialInterface.java ├── Factorial.java ├── README.md ├── Baskota_Server.java └── Yashuv_Client.java ├── Banker Algorithm Deadlock Avoidance ├── Banker’s Algorithm for Avoiding Deadlock.pdf └── bankers_deadlock_avoidance_algorithm.cpp ├── RPC Python ├── XML-RPC.txt ├── rpc_client.py └── rpc_server.py ├── Clock Synchronization using Lamport Logical and Vector Timestamp ├── Clock Synchronization (logical & vector).pdf ├── lamport_logical_timestamps.py └── vector_timestamps.py └── README.md /RPC and RMI Implementation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Distributed-System/main/RPC and RMI Implementation.pdf -------------------------------------------------------------------------------- /Election Algorithm - Bully and Ring/Distributed System Election Algorithm.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Distributed-System/main/Election Algorithm - Bully and Ring/Distributed System Election Algorithm.docx -------------------------------------------------------------------------------- /Election Algorithm - Bully and Ring/Election Algorithm Distributed System.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Distributed-System/main/Election Algorithm - Bully and Ring/Election Algorithm Distributed System.pdf -------------------------------------------------------------------------------- /RMI Java/FactorialInterface.java: -------------------------------------------------------------------------------- 1 | import java.rmi.Remote; 2 | import java.rmi.RemoteException; 3 | 4 | public interface FactorialInterface extends Remote { 5 | int factorial(int n) throws RemoteException; 6 | } 7 | -------------------------------------------------------------------------------- /Banker Algorithm Deadlock Avoidance/Banker’s Algorithm for Avoiding Deadlock.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Distributed-System/main/Banker Algorithm Deadlock Avoidance/Banker’s Algorithm for Avoiding Deadlock.pdf -------------------------------------------------------------------------------- /RPC Python/XML-RPC.txt: -------------------------------------------------------------------------------- 1 | XML-RPC is a remote procedure call (RPC) protocol which uses XML to encode its calls and HTTP as a transport mechanism. 2 | In XML-RPC, a client performs an RPC by sending an HTTP request to a server that implements XML-RPC and receives the HTTP response. -------------------------------------------------------------------------------- /Clock Synchronization using Lamport Logical and Vector Timestamp/Clock Synchronization (logical & vector).pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yashuv/Distributed-System/main/Clock Synchronization using Lamport Logical and Vector Timestamp/Clock Synchronization (logical & vector).pdf -------------------------------------------------------------------------------- /RMI Java/Factorial.java: -------------------------------------------------------------------------------- 1 | public class Factorial implements FactorialInterface { 2 | public int factorial(int n) { 3 | int fact = 1; 4 | for (int i = 1; i <= n; i++) { 5 | fact = fact * i; 6 | } 7 | return fact; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /RPC Python/rpc_client.py: -------------------------------------------------------------------------------- 1 | 2 | # Importing xmlrpc client 3 | import xmlrpc.client 4 | 5 | # specify the server in .ServerProxy 6 | with xmlrpc.client.ServerProxy('http://127.0.0.1:8000/') as proxy: 7 | 8 | # client performs an RPC by sending an HTTP request to a server 9 | while True: 10 | n = int(input('\tEnter number for Factorial: ')) 11 | print("\t",n,"! = ",proxy.factorial(n), end='\n\n') -------------------------------------------------------------------------------- /RMI Java/README.md: -------------------------------------------------------------------------------- 1 |

Trying RMI

2 |

🔸 In three different terminal windows:

3 | 4 |
    5 |
  1. 6 | Run the registry program using command:
    7 |    ⚬ run rmiregistry 8 |
  2. 9 |
  3. 10 | Run the server program:
    11 |    ⚬ java Baskota_Server 12 |
  4. 13 |
  5. 14 | Run the client program:
    15 |    ⚬ java Yashuv_Client 16 |
  6. 17 |
18 | 🔸 If all goes well, you shoud get factorial program. 19 |
20 | -------------------------------------------------------------------------------- /RPC Python/rpc_server.py: -------------------------------------------------------------------------------- 1 | 2 | # firstly, importing from xmlrpc.server, SimpleXMLRPCServer 3 | from xmlrpc.server import SimpleXMLRPCServer 4 | 5 | # Start the server 6 | with SimpleXMLRPCServer(('127.0.0.1', 8000)) as server: 7 | 8 | print("Listening on port 8000...") 9 | 10 | def factorial(n): 11 | if (n==0 or n==1): 12 | return 1 13 | else: 14 | return n * factorial(n-1) 15 | 16 | # register the name and function (both) when calling the server from the client 17 | server.register_function(factorial, "factorial") 18 | server.serve_forever() -------------------------------------------------------------------------------- /RMI Java/Baskota_Server.java: -------------------------------------------------------------------------------- 1 | import java.rmi.registry.Registry; 2 | import java.rmi.registry.LocateRegistry; 3 | import java.rmi.server.UnicastRemoteObject; 4 | 5 | public class Baskota_Server extends Factorial { 6 | public Baskota_Server() { 7 | } 8 | public static void main(String args[]) { 9 | try { 10 | Factorial obj = new Factorial(); 11 | FactorialInterface stub = (FactorialInterface) UnicastRemoteObject.exportObject(obj, 0); 12 | Registry registry = LocateRegistry.getRegistry(); 13 | registry.bind("FactorialInterface", stub); 14 | System.err.println("Server is ready..."); 15 | } catch (Exception e) { 16 | System.err.println("Server exception: " + e.toString()); 17 | e.printStackTrace(); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /RMI Java/Yashuv_Client.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.rmi.registry.LocateRegistry; 3 | import java.rmi.registry.Registry; 4 | 5 | public class Yashuv_Client { 6 | private Yashuv_Client() { 7 | } 8 | 9 | public static void main(String[] args) { 10 | Scanner in = new Scanner(System.in); 11 | try { 12 | Registry registry = LocateRegistry.getRegistry(null); 13 | FactorialInterface stub = (FactorialInterface) registry.lookup("FactorialInterface"); 14 | 15 | while (true) { 16 | System.out.print("Enter nummber for factorial: "); 17 | int n = in.nextInt(); 18 | System.out.println(stub.factorial(n)); 19 | } 20 | } catch (Exception e) { 21 | System.err.println("Client exception: " + e.toString()); 22 | e.printStackTrace(); 23 | } finally { 24 | in.close(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Clock Synchronization using Lamport Logical and Vector Timestamp/lamport_logical_timestamps.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pprint # to prettify our dictionary 3 | 4 | processList =[] 5 | logicalClock = {} 6 | TimeStamp = {} 7 | 8 | def addProcess(): 9 | pName = input("Enter Processes Name seperated by space: ") 10 | processList = pName.split() 11 | for process in processList: 12 | logicalClock[process] = 0 13 | 14 | def sendMessage(t): 15 | eName = input("Enter the Event which will receive the message: ") 16 | pName = input("Enter the process on which this event will occur: ") 17 | if t > logicalClock[pName]: 18 | logicalClock[pName] = t 19 | TimeStamp[eName] = logicalClock[pName] + 1 20 | logicalClock[pName] += 1 21 | 22 | def addEvent(): 23 | pName = input("Enter the Process for which you want to add an event: ") 24 | eName = input("Enter Event Name: ") 25 | eType = input("Enter the type of event(normal/message): ") 26 | if eType == "normal": 27 | TimeStamp[eName] = logicalClock[pName] + 1 28 | logicalClock[pName] += 1 29 | if eType == "message": 30 | TimeStamp[eName] = logicalClock[pName] + 1 31 | logicalClock[pName] += 1 32 | sendMessage(TimeStamp[eName]) 33 | 34 | def display(): 35 | print("-"*20) 36 | pprint.pprint(TimeStamp) 37 | 38 | 39 | if __name__ == "__main__": 40 | addProcess() 41 | while(1): 42 | print("-"*20) 43 | print("1.ADD EVENT\n2.DISPLAY TIMESTAMP\n3.EXIT") 44 | print("-"*20) 45 | n = int(input("Enter your choice: ")) 46 | if n==1: 47 | addEvent() 48 | elif n==2: 49 | display() 50 | else: 51 | sys.exit("BYE") 52 | -------------------------------------------------------------------------------- /Clock Synchronization using Lamport Logical and Vector Timestamp/vector_timestamps.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import pprint 3 | 4 | processList =[] 5 | vectorClock = {} 6 | TimeStamp = {} 7 | 8 | def addProcess(): 9 | global processList 10 | pName = input("Enter Processes Name seperated by space: ") 11 | processList = pName.split() 12 | for process in processList: 13 | vectorClock[process] = [0] * len(processList) 14 | 15 | def sendMessage(t): 16 | eName = input("Enter the Event which will receive the message: ") 17 | pName = input("Enter the process on which this event will occur: ") 18 | pval = int(pName[-1]) 19 | for i in range(len(processList)): 20 | # print('(vectorClock[',pName,'][',i,'], t[',i,']) =', '(',vectorClock[pName][i],', ', t[i],')') 21 | vectorClock[pName][i] = max(vectorClock[pName][i], t[i]) 22 | 23 | vectorClock[pName][pval-1] += 1 24 | vec = vectorClock[pName].copy() 25 | TimeStamp.update({eName:vec}) 26 | 27 | 28 | def addEvent(): 29 | pName = input("Enter the Process for which you want to add an event: ") 30 | eName = input("Enter Event Name: ") 31 | eType = input("Enter the type of event(normal/message): ") 32 | pval = int(pName[-1]) 33 | 34 | vectorClock[pName][pval-1] += 1 35 | 36 | vec = vectorClock[pName].copy() 37 | 38 | if eType == "normal" or eType == "n" or eType == "N": 39 | TimeStamp.update({eName:vec}) 40 | 41 | if eType == "message" or eType == "m" or eType == "M": 42 | TimeStamp.update({eName:vec}) 43 | sendMessage(TimeStamp[eName]) 44 | 45 | 46 | def display(): 47 | print("-"*20) 48 | pprint.pprint(TimeStamp) 49 | print("-"*20) 50 | 51 | 52 | if __name__ == "__main__": 53 | addProcess() 54 | while(1): 55 | print("-"*20) 56 | print("1.ADD EVENT\n2.DISPLAY TIMESTAMP\n3.EXIT") 57 | print("-"*20) 58 | n = int(input("Enter your choice: ")) 59 | if n==1: 60 | addEvent() 61 | elif n==2: 62 | display() 63 | else: 64 | sys.exit("BYE") 65 | -------------------------------------------------------------------------------- /Banker Algorithm Deadlock Avoidance/bankers_deadlock_avoidance_algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define n 3 4 | #define m 4 5 | using namespace std; 6 | 7 | void computeNeed(int need[n][m], int maximum[n][m], int allocated[n][m]); 8 | 9 | bool isSystemSafe(int process[n], int available[m], int maximum[n][m], int allocated[n][m]); 10 | 11 | int main() 12 | { 13 | // Total number of processes 14 | int process[n] = {0, 1, 2}; 15 | 16 | // Available units of resources 17 | int available[m] = {3, 1, 1, 2}; 18 | 19 | // Maximum units of resources that can be allocated to processes 20 | int maximum[n][m] = {{3, 3, 2, 2}, 21 | {1, 2, 3, 4}, 22 | {1, 3, 5, 0}}; 23 | 24 | // Resources currently allocated to processes 25 | int allocated[n][m] = {{1, 2, 2, 1}, 26 | {1, 0, 3, 3}, 27 | {1, 2, 1, 0}}; 28 | 29 | // Check whether the system is in safe state or not 30 | isSystemSafe(process, available, maximum, allocated); 31 | 32 | return 0; 33 | } 34 | 35 | void computeNeed(int need[n][m], int maximum[n][m], int allocated[n][m]) 36 | { 37 | 38 | for (int i = 0; i < n; i++) 39 | for (int j = 0; j < m; j++) 40 | need[i][j] = maximum[i][j] - allocated[i][j]; 41 | } 42 | 43 | bool isSystemSafe(int process[n], int available[m], int maximum[n][m], int allocated[n][m]) 44 | { 45 | int i, j, k; 46 | bool flag; 47 | 48 | int need[n][m]; 49 | 50 | // First we compute need 51 | computeNeed(need, maximum, allocated); 52 | 53 | // Initially all processes are marked as unfinished 54 | bool finished[n] = {false}; 55 | 56 | // Array to store the safe sequence of execution 57 | int safeSequence[n]; 58 | 59 | // Since we will be mutating available array, 60 | // we make its copy and work on that copy 61 | int copyAvailable[m]; 62 | for (i = 0; i < m; i++) 63 | copyAvailable[i] = available[i]; 64 | 65 | int count = 0; 66 | while (count < n) 67 | { 68 | // Find a process which is unfinished and whose need can be 69 | // satisfied from current available resources 70 | flag = false; 71 | for (i = 0; i < n; i++) 72 | { 73 | if (!finished[i]) 74 | { 75 | // Check if all of the process need 76 | // is less than available 77 | for (j = 0; j < m; j++) 78 | if (need[i][j] > copyAvailable[j]) 79 | break; 80 | // If all of the process need are less 81 | // than what is available 82 | if (j == m) 83 | { 84 | // This means that the process can finish 85 | // its execution and when it finishes then 86 | // we can free the resources it was using 87 | for (k = 0; k < m; k++) 88 | copyAvailable[k] += allocated[i][k]; 89 | 90 | // This process can be executed safely 91 | safeSequence[count++] = i; 92 | 93 | // This process is finished 94 | finished[i] = true; 95 | 96 | flag = true; 97 | } 98 | } 99 | } 100 | if (flag == false) 101 | { 102 | cout << "System is not in a safe state " << endl; 103 | return false; 104 | } 105 | } 106 | cout << "System is in safe state.\nSafe sequence is: "; 107 | for (int i = 0; i < n; i++) 108 | cout <<'P' << safeSequence[i] << "\t"; 109 | return true; 110 | } 111 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Distributed-System 2 | 3 | I tried to give some insights and provide the simulated code for the Election Algorithm (Bully and Ring), RPC and RMI, Clock Synchronization using Lamport logical timestamp and Vector timestamp, and Banker's Deadlock Avoidance Algorithm. 4 |

5 | ------------------------------------- Clock Synchronization In Distributed System ----------------------------------------------
6 | 🔶 Using Lamport’s Algorithm

7 | ![image](https://user-images.githubusercontent.com/66567559/178660323-a7f54e82-a30e-41ff-9d28-08e89d60dfe6.png) 8 |

9 | Program Output:
10 | ![image](https://user-images.githubusercontent.com/66567559/178660732-bf7b4900-9ebc-4ba1-8a7c-9633c555d7a7.png) 11 |

12 | 🔶 Using Vector Timestamp

13 | ![image](https://user-images.githubusercontent.com/66567559/178661244-3e5166f1-b3c6-455a-974c-790795c12c8e.png) 14 |

15 | Program Output:
16 | ![image](https://user-images.githubusercontent.com/66567559/178661419-06cec436-2567-42cd-a546-4397011f03d9.png) 17 |
18 | More here 19 |
20 | ---------------------------------------- Leader Election in Distributed System --------------------------------------------------
21 | The main purpose of the leader election is to choose a node as a coordinator. It will act as a leader and coordinate activities of the whole system.The election algorithm assumes that every active process in the system has a unique priority number. A leader in any leader election algorithm is usually chosen based on the node which has the largest identifier. Hence, when a coordinator fails, this algorithm elects the active process that has the highest priority number. Then this number is sent to every active process in the distributed system.

22 | 🔶 Bully Algorithm

23 | In a distributed system, when the leader is crashed, other nodes must elect another leader. The election algorithm we consider here is called the bully algorithm because the node with the highest ID forces the nodes with smaller ID into accepting it as a coordinator.
24 | Simulated Program Output
25 | ![image](https://user-images.githubusercontent.com/66567559/178666002-6a9479da-3a2c-469a-a3e5-c1e885eb41b4.png) 26 |

27 | Analysis:
28 | Initially, among the five processes, process with ID:5 is the one with the highest ID, so it is selected as 29 | a leader. After that, the process with ID:5 crashes and since process with ID:4 is dead, process with 30 | ID:3 is selected as leader. After some time, the process with ID:4 activates and calls for election. Since, 31 | process with ID:5 is dead, the process with ID:4 is selected as leader. 32 |

33 | 🔶 Ring Algorithm

34 | This algorithm applies to systems organized as a ring (logically or physically). In this algorithm, 35 | we assume that the links between the processes are unidirectional and that every process can 36 | message the process on its right only.

37 | Simulated Program Output
38 | ![444](https://user-images.githubusercontent.com/66567559/178669266-d7be0e4d-087c-49a6-ad47-405ba86ebe42.jpg) 39 |

40 | More here
41 | ------------------------------------------------------------------------------------------------------------------------------
42 | 🔶 Bankers Algorithm

43 | A new deadlock avoidance algorithm, derived from Dijkstra’s Bankers Algorithm, is introduced for avoiding deadlock and allocate resources safely to each process in a distributed SOA. The algorithm works by observing the current state of the resources in the system along with a worst case estimate of future resource requirements and permitting the execution of only those call trees that will keep the system in a safe state. 44 | 45 | More here
46 | ------------------------------------------------------------------------------------------------------------------------------
47 | Thank You.. HappY Learning! 48 | 49 | 50 | -------------------------------------------------------------------------------- /Election Algorithm - Bully and Ring/bully_ring_election_algorithm.py: -------------------------------------------------------------------------------- 1 | # we define MAX as the maximum number of processes our program can simulate 2 | # we declare pStatus to store the process status; 0 for dead and 1 for alive 3 | # we declare n as the number of processes 4 | # we declare coordinator to store the winner of election 5 | 6 | MAX = 20 7 | pStatus = [0 for _ in range(MAX)] 8 | n = 0 9 | coordinator = 0 10 | 11 | # def take_input(): 12 | # global coordinator,n 13 | # n = int(input("Enter number of processes: ")) 14 | # for i in range(1, n+1): 15 | # print("Enter Process ",i, " is alive or not(0/1): ") 16 | # x = int(input()) 17 | # pStatus[i] = x 18 | # if pStatus[i]: 19 | # coordinator = i 20 | 21 | def bully(): 22 | " bully election implementation" 23 | global coordinator 24 | condition = True 25 | while condition: 26 | print('---------------------------------------------') 27 | print("1.CRASH\n2.ACTIVATE\n3.DISPLAY\n4.EXIT") 28 | print('---------------------------------------------\n') 29 | print("Enter your choice: ", end='') 30 | schoice = int(input()) 31 | 32 | if schoice == 1: 33 | # we manually crash the process to see if our implementation 34 | # can elect another leader 35 | print("Enter process to crash: ", end='') 36 | crash = int(input()) 37 | # if the process is alive then set its status to dead 38 | if (pStatus[crash] != 0): 39 | pStatus[crash] = 0 40 | else: 41 | print('Process', crash, ' is already dead!\n') 42 | break 43 | condition = True 44 | while condition: 45 | # enter another process to initiate the election 46 | print("Enter election generator id: ", end='') 47 | gid = int(input()) 48 | if (gid == coordinator or pStatus[gid] == 0): 49 | print("Enter a valid generator id!") 50 | condition = (gid == coordinator or pStatus[gid] == 0) 51 | flag = 0 52 | # if the coordinator has crashed then we need to find another leader 53 | if (crash == coordinator): 54 | # the election generator process will send the message to all higher process 55 | i = gid + 1 56 | while i <= n: 57 | print("Message is sent from", gid, " to", i, end='\n') 58 | # if the higher process is alive then it will respond 59 | if (pStatus[i] != 0): 60 | subcoordinator = i 61 | print("Response is sent from", i, " to", gid, end='\n') 62 | flag = 1 63 | i += 1 64 | # the highest responding process is selected as the leader 65 | if (flag == 1): 66 | coordinator = subcoordinator 67 | # else if no higher process are alive then the election generator process 68 | # is selected as leader 69 | else: 70 | coordinator = gid 71 | display() 72 | 73 | elif schoice == 2: 74 | # enter process to revive 75 | print("Enter Process ID to be activated: ", end='') 76 | activate = int(input()) 77 | # if the entered process was dead then it is revived 78 | if (pStatus[activate] == 0): 79 | pStatus[activate] = 1 80 | else: 81 | print("Process", activate, " is already alive!", end='\n') 82 | break 83 | # if the highest process is activated then it is the leader 84 | if (activate == n): 85 | coordinator = n 86 | break 87 | flag = 0 88 | # else, the activated process sends message to all higher process 89 | i = activate + 1 90 | while i <= n: 91 | print("Message is sent from", activate, "to", i, end='\n') 92 | # if higher process is active then it responds 93 | if (pStatus[i] != 0): 94 | subcoordinator = i 95 | print("Response is sent from", i, 96 | "to", activate, end='\n') 97 | flag = 1 98 | i += 1 99 | # the highest responding process is made the leader 100 | if flag == 1: 101 | coordinator = subcoordinator 102 | # if no higher process respond then the activated process is leader 103 | else: 104 | coordinator = activate 105 | display() 106 | 107 | elif schoice == 3: 108 | display() 109 | 110 | elif schoice == 4: 111 | pass 112 | 113 | condition = (schoice != 4) 114 | 115 | def ring(): 116 | " ring election implementation" 117 | global coordinator, n 118 | condition = True 119 | while condition: 120 | print('---------------------------------------------') 121 | print("1.CRASH\n2.ACTIVATE\n3.DISPLAY\n4.EXIT") 122 | print('---------------------------------------------\n') 123 | print("Enter your choice: ", end='') 124 | tchoice = int(input()) 125 | if tchoice == 1: 126 | print("\nEnter process to crash : ", end='') 127 | crash = int(input()) 128 | 129 | if pStatus[crash]: 130 | pStatus[crash] = 0 131 | else: 132 | print("Process", crash, "is already dead!", end='\n') 133 | condition = True 134 | while condition: 135 | print("Enter election generator id: ", end='') 136 | gid = int(input()) 137 | if gid == coordinator: 138 | print("Please, enter a valid generator id!", end='\n') 139 | condition = (gid == coordinator) 140 | 141 | if crash == coordinator: 142 | subcoordinator = 1 143 | i = 0 144 | while i < (n+1): 145 | pid = (i + gid) % (n+1) 146 | if pid != 0: # since our process starts from 1 (to n) 147 | if pStatus[pid] and subcoordinator < pid: 148 | subcoordinator = pid 149 | print("Election message passed from", pid, ": #Msg", subcoordinator, end='\n') 150 | i += 1 151 | 152 | coordinator = subcoordinator 153 | display() 154 | 155 | elif tchoice == 2: 156 | print("Enter Process ID to be activated: ", end='') 157 | activate = int(input()) 158 | if not pStatus[activate]: 159 | pStatus[activate] = 1 160 | else: 161 | print("Process", activate, "is already alive!", end='\n') 162 | break 163 | 164 | subcoordinator = activate 165 | i = 0 166 | while i < (n+1): 167 | pid = (i + activate) % (n+1) 168 | if pid != 0: # since our process starts from 1 (to n) 169 | if pStatus[pid] and subcoordinator < pid: 170 | subcoordinator = pid 171 | print("Election message passed from", pid, 172 | ": #Msg", subcoordinator, end='\n') 173 | i += 1 174 | 175 | coordinator = subcoordinator 176 | display() 177 | 178 | elif tchoice == 3: 179 | display() 180 | 181 | condition = tchoice != 4 182 | 183 | 184 | def choice(): 185 | """ choice of options """ 186 | while True: 187 | print('---------------------------------------------') 188 | print("1.BULLY ALGORITHM\n2.RING ALGORITHM\n3.DISPLAY\n4.EXIT") 189 | print('---------------------------------------------\n') 190 | fchoice = int(input("Enter your choice: ")) 191 | 192 | if fchoice == 1: 193 | bully() 194 | elif fchoice == 2: 195 | ring() 196 | elif fchoice == 3: 197 | display() 198 | elif fchoice == 4: 199 | exit(0) 200 | else: 201 | print("Please, enter valid choice!") 202 | 203 | 204 | def display(): 205 | """ displays the processes, their status and the coordinator """ 206 | global coordinator 207 | print('---------------------------------------------') 208 | print("PROCESS:", end=' ') 209 | for i in range(1, n+1): 210 | print(i, end='\t') 211 | print('\nALIVE:', end=' ') 212 | for i in range(1, n+1): 213 | print(pStatus[i], end='\t') 214 | print('\n---------------------------------------------') 215 | print('COORDINATOR IS', coordinator, end='\n') 216 | # print('----------------------------------------------') 217 | 218 | 219 | if __name__ == '__main__': 220 | 221 | # take_input() 222 | 223 | n = int(input("Enter number of processes: ")) 224 | for i in range(1, n+1): 225 | print("Enter Process ", i, " is alive or not(0/1): ") 226 | x = int(input()) 227 | pStatus[i] = x 228 | if pStatus[i]: 229 | coordinator = i 230 | 231 | display() 232 | choice() 233 | -------------------------------------------------------------------------------- /Election Algorithm - Bully and Ring/bully_and_ring_election_algorithm.cpp: -------------------------------------------------------------------------------- 1 | // first we include the necessary header files 2 | #include 3 | #include 4 | 5 | // we define MAX as the maximum number of processes our program can simulate 6 | // we declare array pStatus[MAX] to store the process status; 0 for dead and 1 for alive 7 | // we declare n as the number of processes 8 | // we declare coordinator to store the winner of election 9 | 10 | #define MAX 20 11 | 12 | int pStatus[MAX], n, coordinator; 13 | using namespace std; 14 | 15 | // we declare the necessary functions 16 | void bully(); 17 | void ring(); 18 | // void ring_(); // this is also another approach ring implementation, and works well. 19 | void display(); 20 | 21 | int main() 22 | { 23 | int i, j, fchoice; 24 | cout << "Enter number of processes: "; 25 | cin >> n; 26 | for (i = 1; i <= n; i++) 27 | { 28 | cout << "Enter Process " << i << " is alive or not(0/1): "; 29 | cin >> pStatus[i]; 30 | if (pStatus[i]) 31 | coordinator = i; 32 | } 33 | display(); 34 | do 35 | { 36 | cout << "-------------------------------------------------"; 37 | cout << "\n1.BULLY ALGORITHM\n2.RING\n3.DISPLAY\n4.EXIT\n"; 38 | cout << "-------------------------------------------------\n\n"; 39 | cout << "Enter your choice: "; 40 | cin >> fchoice; 41 | switch (fchoice) 42 | { 43 | case 1: 44 | bully(); 45 | break; 46 | case 2: 47 | ring(); 48 | // ring_() 49 | break; 50 | case 3: 51 | display(); 52 | break; 53 | case 4: 54 | exit(1); 55 | break; 56 | } 57 | } while (fchoice != 3); 58 | return 0; 59 | } 60 | 61 | void display() 62 | { 63 | int i; 64 | // we display the processes, their status and the coordinator 65 | cout << "-------------------------------------------------\n"; 66 | cout << "Processes: "; 67 | for (i = 1; i <= n; i++) // PID from 1 to n 68 | cout << i << "\t"; 69 | cout << endl 70 | << "Alive: "; 71 | for (i = 1; i <= n; i++) 72 | cout << pStatus[i] << "\t"; 73 | cout << "\n-------------------------------------------------\n"; 74 | cout << "COORDINATOR IS " << coordinator << endl; 75 | } 76 | 77 | // bully algorithm implementation 78 | void bully() 79 | { 80 | int schoice, crash, activate, i, gid, flag, subcoordinator; 81 | do 82 | { 83 | cout << "-------------------------------------------------"; 84 | cout << "\n1.CRASH\n2.ACTIVATE\n3.DISPLAY\n4.EXIT\n"; 85 | cout << "-------------------------------------------------\n"; 86 | cout << "Enter your choice: "; 87 | cin >> schoice; 88 | switch (schoice) 89 | { 90 | case 1: 91 | // we manually crash the process to see if our implementation 92 | // can elect another coordinator 93 | cout << "Enter process to crash: "; 94 | cin >> crash; 95 | // if the process is alive then set its status to dead 96 | if (pStatus[crash]) 97 | pStatus[crash] = 0; 98 | else 99 | cout << "Process " << crash << " is already dead!" << endl; 100 | do 101 | { 102 | // enter another process to initiate the election 103 | cout << "Enter election generator id: "; 104 | cin >> gid; 105 | if (gid == coordinator || pStatus[gid] == 0) 106 | cout << "Please, enter a valid generator id.." << endl; 107 | } while (gid == coordinator || pStatus[gid] == 0); 108 | flag = 0; 109 | // if the coordinator has crashed then we need to find another coordinator 110 | if (crash == coordinator) 111 | { 112 | // the election generator process will send the message to all higher process 113 | for (i = gid + 1; i <= n; i++) 114 | { 115 | cout << "Message is sent from " << gid << " to " << i << endl; 116 | // if the higher process is alive then it will respond 117 | if (pStatus[i]) 118 | { 119 | subcoordinator = i; 120 | cout << "Response is sent from " << i << " to " << gid << endl; 121 | flag = 1; 122 | } 123 | } 124 | // the highest responding process is selected as the coordinator 125 | if (flag == 1) 126 | coordinator = subcoordinator; 127 | // else if no higher process are alive then the election generator process 128 | // is selected as coordinator 129 | else 130 | coordinator = gid; 131 | } 132 | display(); 133 | break; 134 | case 2: 135 | // enter process to revive 136 | cout << "Enter Process ID to be activated: "; 137 | cin >> activate; 138 | // if the entered process was dead then it is revived 139 | if (!pStatus[activate]) 140 | { 141 | pStatus[activate] = 1; 142 | } 143 | else 144 | { 145 | cout << "Process " << activate << " is already alive!" << endl; 146 | break; 147 | } 148 | // if the highest process is activated then it is the coordinator 149 | if (activate == n) 150 | { 151 | coordinator = n; 152 | break; 153 | } 154 | flag = 0; 155 | // else, the activated process sends message to all higher process 156 | for (i = activate + 1; i <= n; i++) 157 | { 158 | cout << "Message is sent from " << activate << " to " << i << endl; 159 | // if higher process is active then it responds 160 | if (pStatus[i]) 161 | { 162 | subcoordinator = i; 163 | cout << "Response is sent from " << i << " to " << activate << endl; 164 | flag = 1; 165 | } 166 | } 167 | // the highest responding process is made the coordinator 168 | if (flag == 1) 169 | coordinator = subcoordinator; 170 | // if no higher process respond then the activated process is coordinator 171 | else 172 | coordinator = activate; 173 | display(); 174 | break; 175 | case 3: 176 | display(); 177 | break; 178 | case 4: 179 | break; 180 | } 181 | } while (schoice != 4); 182 | } 183 | 184 | // ring algorithm implementation 185 | void ring() 186 | { 187 | int tchoice, crash, activate, gid, subcoordinator, i; 188 | do 189 | { 190 | cout << "-------------------------------------------------"; 191 | cout << "\n1.CRASH\n2.ACTIVATE\n3.DISPLAY\n4.EXIT\n"; 192 | cout << "-------------------------------------------------\n\n"; 193 | cout << "Enter your choice: "; 194 | cin >> tchoice; 195 | switch (tchoice) 196 | { 197 | case 1: 198 | cout << "\nEnter Process ID to crash : "; 199 | cin >> crash; 200 | 201 | if (pStatus[crash]) 202 | pStatus[crash] = 0; 203 | else 204 | cout << "Process " << crash << " is already dead!" << endl; 205 | do 206 | { 207 | cout << "Enter election generator id: "; 208 | cin >> gid; 209 | if (gid == coordinator) 210 | cout << "Please, enter a valid generator id.." << endl; 211 | } while (gid == coordinator); 212 | 213 | if (crash == coordinator) 214 | { 215 | subcoordinator = 1; 216 | for (i = 0; i < (n + 1); i++) 217 | { 218 | int pid = (i + gid) % (n + 1); 219 | if (pid != 0) // since process id starts from 1 (to n) 220 | { 221 | if (pStatus[pid] && subcoordinator < pid) 222 | { 223 | subcoordinator = pid; 224 | } 225 | cout << "Election message sent from " << pid << ": #Msg" << subcoordinator << endl; 226 | } 227 | } 228 | 229 | coordinator = subcoordinator; 230 | } 231 | display(); 232 | break; 233 | 234 | case 2: 235 | cout << "Enter Process ID to be activated: "; 236 | cin >> activate; 237 | if (!pStatus[activate]) 238 | pStatus[activate] = 1; 239 | else 240 | { 241 | cout << "Process " << activate << " is already alive!" << endl; 242 | break; 243 | } 244 | 245 | subcoordinator = activate; 246 | for (i = 0; i < n + 1; i++) 247 | { 248 | int pid = (i + activate) % (n + 1); 249 | 250 | if (pid != 0) 251 | { 252 | if (pStatus[pid] && subcoordinator < pid) 253 | { 254 | subcoordinator = pid; 255 | } 256 | cout << "Election message passed from " << pid << ": #Msg" << subcoordinator << endl; 257 | } 258 | } 259 | 260 | coordinator = subcoordinator; 261 | display(); 262 | break; 263 | 264 | case 3: 265 | display(); 266 | break; 267 | 268 | default: 269 | break; 270 | } 271 | } while (tchoice != 4); 272 | } 273 | 274 | // ring algorithm implementation (another approach) 275 | // void ring_() 276 | // { 277 | // int activePID[MAX], PID, k, temp; 278 | // int tchoice, crash, activate, i, generatorid, flag, subordinator; 279 | // do 280 | // { 281 | // cout << "-------------------------------------------------"; 282 | // cout << "\n1.CRASH\n2.ACTIVATE\n3.DISPLAY\n4.EXIT\n"; 283 | // cout << "-------------------------------------------------\n"; 284 | // cout << "Enter your choice: "; 285 | // cin >> tchoice; 286 | // switch (tchoice) 287 | // { 288 | // case 1: 289 | // cout << "\nEnter Process to Crash: "; 290 | // cin >> crash; // process to be crashed id is given 291 | // if (pStatus[crash]) // check whether process is alive or dead 292 | // pStatus[crash] = 0; 293 | // else 294 | // { 295 | // cout << "\nProcess is alreaady dead!!"; 296 | // break; 297 | // } 298 | // // election generation 299 | // do 300 | // { 301 | // cout << "\nEnter election generator id:"; 302 | 303 | // cin >> generatorid; 304 | 305 | // if (generatorid == coordinator) // check whether generator is cordinator 306 | // { 307 | // cout << "\nPlease,enter a valid generator id..." << endl; 308 | // } 309 | // } while (generatorid == coordinator); 310 | // flag = 0; 311 | // k = 1; 312 | // if (crash == coordinator) // election is meaningful if crashed process is coordinator 313 | // { 314 | // activePID[k] = generatorid; 315 | // PID = generatorid; 316 | // for (i = (generatorid + 1) % n; i != generatorid; i = (i + 1) % n) 317 | // { 318 | // if (i != 0) 319 | // { 320 | // if (pStatus[i]) 321 | // { 322 | // cout << "\nMessage is sent from " << PID << " to " << i; 323 | // activePID[k++] = i; 324 | // PID++; 325 | // } 326 | // } 327 | // } 328 | // subordinator = 1; 329 | // for (i = 1; i < k; i++) 330 | // { 331 | // if (subordinator < activePID[i]) 332 | // { 333 | // subordinator = activePID[i]; 334 | // } 335 | // } 336 | 337 | // coordinator = subordinator; 338 | // for (i = 1; i < k; i++) 339 | // { 340 | // cout << "\n" 341 | // << coordinator << " is coordinator message to " << activePID[i] << endl; 342 | // } 343 | // } 344 | // display(); 345 | // break; 346 | 347 | // case 2: 348 | // // activate 349 | // cout << "\nEnter Process to Activate: "; 350 | // cin >> activate; 351 | // if (!pStatus[activate]) // activate the process 352 | // pStatus[activate] = 1; 353 | // else 354 | // { 355 | // cout << "\nProcess is already alive!" << endl; 356 | // break; 357 | // } 358 | 359 | // if (activate == n) // if highest id process is activated 360 | // { 361 | // coordinator = n; // then automatically it is coordinator 362 | // break; 363 | // } 364 | // temp = activate; 365 | // for (i = (activate + 1) % (n + 1); i != activate; i = (i + 1) % (n + 1)) 366 | // { 367 | // if (i != 0) 368 | // { 369 | // cout << "Message is sent from " << temp << " to " << i << endl; 370 | // if (pStatus[i] && i > activate) 371 | 372 | // { 373 | // subordinator = i; 374 | // cout << "\nResponse is sent from " << i << " to " << temp << endl; 375 | // flag = 1; 376 | // } 377 | // temp = (temp + 1) % (n + 1); 378 | // if (temp == 0) 379 | // { 380 | // temp++; 381 | // } 382 | // } 383 | // } 384 | // if (flag == 1) 385 | // { 386 | // coordinator = subordinator; 387 | // } 388 | // else 389 | // { 390 | // coordinator = activate; 391 | // } 392 | // display(); 393 | // break; 394 | // case 3: 395 | // display(); 396 | // break; 397 | // case 4: 398 | // break; 399 | // } 400 | // } while (tchoice != 4); 401 | // } 402 | --------------------------------------------------------------------------------