KaranThakkar PDCExp06

You might also like

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

Academic Year 2022-23 SAP: 60003200097

DEPARTMENT OF INFORMATION TECHNOLOGY


COURSE CODE: DJ19ITL601
COURSE NAME: Parallel and Distributed Computing CLASS: T Y B. TECH

NAME: Karan Thakkar SAP: 60003200097

LAB EXPERIMENT NO. 6

CO/LO: Implementation of Mutual Exclusion for Distributed environment.


AIM / OBJECTIVE: To implement Centralized and Distributed mutual exclusion algorithms.

INSTRUCTIONS:
i. Centralized Algorithm

ii. Distributed Algorithm (Ricart Agrawala Algorithm)


1. Two processes want to enter the same critical region at the same moment.
2. Process 0 has the lowest timestamp, so it wins.
3. When Process 0 is done, it sends an OK, so Process 2 can now enter the critical region.

Example:
Academic Year 2022-23 SAP: 60003200097

Source Code:

Centralized Algorithm
Client.java

package Centralized;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
    boolean permissionCS = false;
    private Socket socket = null;
    private DataInputStream input = null;
    private DataOutputStream out = null;

    public Client(String address, int port) {


        try {
            socket = new Socket(address, port);
            System.out.println("Connected");
            input = new DataInputStream(socket.getInputStream());
            out = new DataOutputStream(socket.getOutputStream());
        } catch (UnknownHostException u) {
            System.out.println(u);
        } catch (IOException i) {
            System.out.println(i);
        }
    }

    public boolean requestCriticalSection() {


        boolean request = false;
        String requestMessage = "REQUEST_CS";
        String responseMessage = "";
        try {
            out.writeUTF(requestMessage);
            out.flush();
            responseMessage = input.readUTF();
            System.out.println("Message received from server: " +
responseMessage);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            if (responseMessage.equals("GRANT_CS")) {
                request = true;
            }
Academic Year 2022-23 SAP: 60003200097

        }
        return request;
    }

    public boolean exitCriticalSection() {


        String requestMessage = "EXIT_CS";
        String responseMessage = "";
        boolean request = true;
        try {
            out.writeUTF(requestMessage);
            out.flush();
            responseMessage = input.readUTF();
            System.out.println("Message received from server: " +
responseMessage);
        } catch (IOException e) {
            System.out.println(e);
        } finally {
            if (responseMessage.equals("EXIT_SUCCESS")) {
                request = false;
            }
        }
        return request;
    }

    public static void main(String args[]) {


        Client client = new Client("127.0.0.1", 5000);
        Scanner sc = new Scanner(System.in);
        int option = 0;
        while (option != 3) {
            System.out.println("Options:\n1. Request Critical Section.\
n2. Exit Critical Section.\n3. Exit Program");
            System.out.print("Enter option: ");
            option = sc.nextInt();
            if (option == 1) {
                if (client.permissionCS == true) {
                    System.out.println("Client is already in the
Critical Section");
                } else {
                    client.permissionCS =
client.requestCriticalSection();
                }
            } else if (option == 2) {
                if (client.permissionCS == true) {
                    client.permissionCS = client.exitCriticalSection();
                } else {
                    System.out.println("Client is not in Critical
Section");
                }
            }
        }
Academic Year 2022-23 SAP: 60003200097

        sc.close();
    }
}

CMSServer.java
package Centralized;
import java.io.*;
import java.net.*;
import java.util.*;
public class CMSServer {
    private static ArrayList < Integer > criticalSectionList = new
ArrayList < Integer > (5);
    public static ArrayList < Integer > getCSArray() {
        return CMSServer.criticalSectionList;
    }
    public static void setCSArray(ArrayList < Integer > setArray) {
        CMSServer.criticalSectionList = setArray;
    }
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(5000);
        int clientCounter = 0;
        while (true) {
            Socket s = null;
            try {
                s = ss.accept();
                System.out.printf("A new client is connected : " + s + "\
nClient ID = %d\n", clientCounter);
                DataInputStream dis = new
DataInputStream(s.getInputStream());
                DataOutputStream dos = new
DataOutputStream(s.getOutputStream());
                System.out.println("Assigning new thread for this
client...\n");
                clientCounter++;
                Thread t = new ClientHandler(s, dis, dos, clientCounter);
                t.start();

            } catch (Exception e) {
                s.close();
                e.printStackTrace();
            }
        }
    }
}
class ClientHandler extends Thread {
    final DataInputStream dis;
    final DataOutputStream dos;
    final Socket s;
    final int clientId;
    public ClientHandler(Socket s, DataInputStream dis, DataOutputStream
dos, int clientId) {
Academic Year 2022-23 SAP: 60003200097

        this.s = s;
        this.dis = dis;
        this.dos = dos;
        this.clientId = clientId;
    }
    @Override
    public void run() {
            String receivedMessage;
            String responseMessage;
            ArrayList < Integer > CSArray;
            while (true) {
                try {
                    receivedMessage = dis.readUTF();
                    switch (receivedMessage) {
                        case "REQUEST_CS": {
                            System.out.println("Client " + clientId + "
has requested to enter critical

                                CSArray = CMSServer.getCSArray();
                                if (CSArray.size() == 0) {
                                    CSArray.add(clientId);
                                    responseMessage = "GRANT_CS";
                                    System.out.println(
                                        "Client " + clientId + " has
been granted access to the critical

                                    }
                                    else {
                                        responseMessage = "DENY_CS";
                                        System.out.println(
                                            "Client " + clientId + " has
been denied access to the critical

                                        }
                                        dos.writeUTF(responseMessage);
                                        break;
                                    }
                                    case "EXIT_CS": {
                                        CSArray =
CMSServer.getCSArray();CSArray.clear();
                                        responseMessage =
"EXIT_SUCCESS";System.out.println("Client " + clientId + " has exited
CS.");dos.writeUTF(responseMessage);
                                        break;
                                    }
                                    default: {
                                        dos.writeUTF("Invalid input");
                                        break;
                                    }
                                }
Academic Year 2022-23 SAP: 60003200097

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

OUTPUT:
Server
A new client is connected :
Socket[addr=/127.0.0.1,port=51289,localport=5000] Client ID = 0
Assigning new thread for this client...
A new client is connected :
Socket[addr=/127.0.0.1,port=51292,localport=5000] Client ID = 1
Assigning new thread for this client...
Client 2 has requested to enter critical section
Client 2 has been granted access to the critical
section. Client 1 has requested to enter critical
section
Client 1 has been denied access to the critical
section. Client 2 has exited CS.
Client 1 has requested to enter critical section
Client 1 has been granted access to the critical
section. Client 1 has exited CS.

Client 1
Connected
Options:
1. Request Critical Section.
2. Exit Critical Section.
3. Exit Program
Enter option: 1
Message received from server:
DENY_CS Options:
Academic Year 2022-23 SAP: 60003200097

1. Request Critical Section.


2. Exit Critical Section.
3. Exit Program
Enter option: 1
Message received from server:
GRANT_CS Options:
1. Request Critical Section.
2. Exit Critical Section.
3. Exit Program
Enter option: 2
Message received from server: EXIT_SUCCESS

Client 2
Connected
Options:
1. Request Critical Section.
2. Exit Critical Section.
3. Exit Program
Enter option: 1
Message received from server:
GRANT_CS Options:
1. Request Critical Section.
2. Exit Critical Section.
3. Exit Program
Enter option: 2
Message received from server: EXIT_SUCCESS
Academic Year 2022-23 SAP: 60003200097

Distributed Algorithm
Server.java

import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.io.*;
public class Server extends Node implements Runnable {
    Socket socket = null;
    ServerSocket server = null;
    DataInputStream in = null;
    int port_no;
    int corr_cli_index;
    public Server(int port_no, int cli_index) {
        this.port_no = port_no;
        this.corr_cli_index = cli_index;

    }
    public String read_msg() {
        String res = "";
        try {
            if ( in .available() > 0) {
                String line = (String) in .readUTF();
                System.out.println("Msg received:" + line);
                String res_arr[] = line.split(":", 3);
                if (res_arr[0].equals("REQUEST")) {
                    process_request(res_arr[1], res_arr[2]);
                } else {
                    process_reply(res_arr[1]);
                }
            } else {
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }
        return res;
    }

    synchronized public void process_request(String node_no_str, String


req_no_str) {
        int node_no = Integer.parseInt(node_no_str);
        int req_no = Integer.parseInt(req_no_str);
        if (Node.req_cs_entry) {
            if (req_no < Node.curr_req_no) {
                Node.cliObj.get(corr_cli_index).send_reply(node_no,
"OK");
Academic Year 2022-23 SAP: 60003200097

                if (Node.max_req_no < req_no)


                    Node.max_req_no = req_no;
            } else if (req_no > Node.curr_req_no) {
                Node.def_list.set(node_no, req_no);
                if (Node.max_req_no < req_no)
                    Node.max_req_no = req_no;
            } else {
                if (node_no < Node.node_id) {
                    Node.cliObj.get(corr_cli_index).send_reply(node_no,
"OK");
                    if (Node.max_req_no < req_no)
                        Node.max_req_no = req_no;
                } else {
                    Node.def_list.set(node_no, req_no);
                    System.out.println("Request from Node-" + node_no +
" is deferred. Request Vale:" + req_no);
                    if (Node.max_req_no < req_no) Node.max_req_no =
req_no;
                }
            }

        } else {
            Node.cliObj.get(corr_cli_index).send_reply(node_no, "OK");
            if (Node.max_req_no < req_no)
                Node.max_req_no = req_no;
        }
    }

    synchronized public void process_reply(String msg) {


        try {
            no_of_pending_req = no_of_pending_req - 1;
            if (no_of_pending_req == 0) {
                enter_cs = true;
                Thread.sleep(10);
            }
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }
    }
    public void run() {
        try {
            System.out.println("Server Listening @" + port_no);
            server = new ServerSocket(port_no);
            Thread.sleep(10);
            socket = server.accept(); in = new
DataInputStream(socket.getInputStream());
            System.out.println("Connection Accepted @" + port_no);
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }
Academic Year 2022-23 SAP: 60003200097

        while (true) {
            try {
                read_msg();
                Thread.sleep(10);
            } catch (Exception e) {
                System.out.println("Exception:" + e);

            }
        }
    }
}

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

public class Client extends Node {


    Socket client_socket;
    DataOutputStream client_dout;
    int port_no;
    public Client(int port_no) {
        this.port_no = port_no;
    }
    public void connect(int port_no) {
        Socket socket = null;
        try {
            client_socket = new Socket("localhost", port_no);
            client_dout = new
DataOutputStream(client_socket.getOutputStream());

        } catch (Exception i) {
            System.out.println(i);
        }
    }

    public void send_request(int req_no, int node_no) {


        try {
            client_dout.writeUTF("REQUEST:" + Integer.toString(node_no) +
":" + Integer.toString(req_no));
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }
    }
    public void send_reply(int node_id, String msg) {
        try {
            System.out.println("Sending reply to Node-" + node_id);
            client_dout.writeUTF("REPLY:" + Integer.toString(node_id) +
":OK");
        } catch (Exception e) {
            System.out.println("Exception:" + e);
Academic Year 2022-23 SAP: 60003200097

        }
    }
}

Node.java
import java.util.*;
import java.io.*;
import java.sql.Timestamp;
public class Node {
    static int node_id;
    static boolean enter_cs;
    static int max_nodes;
    static int max_req_no;
    static int curr_req_no;
    static public int no_of_pending_req;
    static boolean req_cs_entry;
    int no_of_times;
    List < String > ip_addr = new ArrayList < String > ();
    List < Integer > port_no = new ArrayList < Integer > ();
    static List < Integer > def_list = new ArrayList < Integer > ();
    static List < Client > cliObj = new ArrayList < Client > ();
    static List < Server > serObj = new ArrayList < Server > ();
    static List < Thread > serThreads = new ArrayList < Thread > ();
    Timestamp ts;
    public Node(int id, int ctr) {
        Node.node_id = id;
        Node.enter_cs = false;
        Node.max_req_no = 0;
        Node.curr_req_no = 0;
        Node.no_of_pending_req = 0;
        Node.req_cs_entry = false;
        this.no_of_times = ctr;
    }
    public void read_config_file() {
        try {
            File file = new File("config.txt");
            BufferedReader br = new BufferedReader(new FileReader(file));
            String str;
            String[] words;
            int node_no;
            boolean firstentry = true;
            while ((str = br.readLine()) != null) {
                if (firstentry) {
                    max_nodes = Integer.parseInt(str);
                    firstentry = false;

                } else {
                    words = str.split(" ");
                    node_no = Integer.parseInt(words[0]);
                    ip_addr.add(node_no, words[1]);
                    port_no.add(node_no, Integer.parseInt(words[2]));
Academic Year 2022-23 SAP: 60003200097

                    def_list.add(node_no, -1);
                }

            }
            br.close();
        } catch (Exception e) {
            System.out.println("Exception:" + e);
        }

    }

    public void cs_pre_requisite() {


        Node.curr_req_no = Node.max_req_no + 1;
        Node.req_cs_entry = true;
        Node.no_of_pending_req = Node.max_nodes - 1;

        for (int i = 0; i < Node.max_nodes; i++) {


            if (i == Node.node_id)
                continue;
            Node.cliObj.get(i).send_request(curr_req_no, Node.node_id);

        }

    }

    public void process_deferred_requests() {


        for (int i = 0; i < def_list.size(); i++) {
            if (def_list.get(i) != -1) {
                String node_no_str = Integer.toString(i);
                String req_no_str = Integer.toString(def_list.get(i));
                Node.serObj.get(i).process_request(node_no_str,
req_no_str);
                def_list.set(i, -1);
            }
        }
    }

    public void Node_main() {


        try {
            read_config_file();
            for (int i = 0; i < Node.max_nodes; i++) {
                if (i == Node.node_id) {
                    Node.serObj.add(i, new Server(0, i));
                    Thread t1 = new Thread(Node.serObj.get(i));
                    Node.serThreads.add(i, t1);
Academic Year 2022-23 SAP: 60003200097

                } else {
                    int temp_port_no = port_no.get(i);
                    Node.serObj.add(i, new Server(temp_port_no +
Node.node_id, i));
                    Thread t1 = new Thread(Node.serObj.get(i));
                    Node.serThreads.add(i, t1);
                    t1.start();
                }
            }
            Thread.sleep(10000);
            for (int i = 0; i < Node.max_nodes; i++) {
                if (i == Node.node_id) {
                    int temp_port_no = port_no.get(i);
                    for (int j = 0; j < Node.max_nodes; j++) {
                        if (j == Node.node_id) {
                            cliObj.add(j, new Client(temp_port_no + j));
                        } else {
                            cliObj.add(j, new Client(temp_port_no + j));
                            cliObj.get(j).connect(temp_port_no + j);
                        }
                    }
                }
            }

            for (int i = 0; i < no_of_times; i++) {


                Thread.sleep(10000);
                cs_pre_requisite();
                while (Node.enter_cs == false) {
                    Thread.sleep(10);
                }
                ts = new Timestamp(System.currentTimeMillis());
                System.out.println("Node-" + node_id + " entered Critical
Section @ " + ts);
                Thread.sleep(2000);
                Node.enter_cs = false;
                Node.req_cs_entry = false;
                ts = new Timestamp(System.currentTimeMillis());
                System.out.println("Node-" + node_id + " exited Critical
Section @ " + ts);
                process_deferred_requests();
            }
            Thread.sleep(10000);
            for (int i = 0; i < Node.max_nodes; i++) {
                if (i != Node.node_id) {
                    serObj.get(i).server.close();
                }
            }
            System.out.println("Completed");
            System.exit(0);
        } catch (Exception e) {
            System.out.println("Exception:" + e);
Academic Year 2022-23 SAP: 60003200097

        }
    }
}

RAMain.java
public class RA_Main {
    public static void main(String[] args) {
        Node nodeObj = new Node(Integer.parseInt(args[0]),
Integer.parseInt(args[1]));
        nodeObj.Node_main();
    }
}

Output:
C:\Users\voras\Desktop>java RA_Main 1 2
Server Listening @4072
Server Listening @4052
Connection Accepted @4052
Connection Accepted @4072
Msg received:REQUEST:0:1
Sending reply to Node-0
Msg received: REPLY:1: OK
Msg received: REQUEST:2:3
Msg received: REPLY:1:OK
Node-1 entered Critical Section @ 2022-05-04 22:58:32.056
Node-1 exited Critical Section @ 2022-05-04 22:58:34.078
Sending reply to Node-2
Msg received:REQUEST:0:4
Sending reply to Node-0
Msg received:REPLY:1:OK
Msg received:REQUEST:2:6
Msg received:REPLY:1:OK
Node-1 entered Critical Section @ 2022-05-04 22:58:52.2
Node-1 exited Critical Section @ 2022-05-04 22:58:54.202
Academic Year 2022-23 SAP: 60003200097

Sending reply to Node-2


Completed C:\Users\
voras\Desktop>

C:\Users\voras\Desktop>java RA_Main 0 2
Server Listening @4071
Server Listening @4061
Connection Accepted @4061
Connection Accepted @4071
Msg received:REPLY:0:OK
Msg received:REQUEST:1:2
Msg received:REPLY:0:OK
Msg received:REQUEST:2:3
Node-0 entered Critical Section @ 2022-05-04 22:58:25.918
Node-0 exited Critical Section @ 2022-05-04 22:58:27.951
Sending reply to Node-1
Sending reply to Node-2
Msg received:REPLY:0:OK
Msg received:REPLY:0:OK
Node-0 entered Critical Section @ 2022-05-04 22:58:46.069
Node-0 exited Critical Section @ 2022-05-04 22:58:48.079
Msg received:REQUEST:1:5
Sending reply to Node-1
Msg received:REQUEST:2:6
Sending reply to Node-2
Completed C:\Users\voras\
Desktop>

Connection Accepted @4053


Connection Accepted @4063
Msg received:REQUEST:0:1
Sending reply to Node-0
Academic Year 2022-23 SAP: 60003200097

Msg received:REQUEST:1:2
Sending reply to Node-1 Msg
received:REPLY:2:OK Msg
received:REPLY:2:OK
Node-2 entered Critical Section @ 2022-05-04 22:58:38.414 Node-
2 exited Critical Section @ 2022-05-04 22:58:40.466 Msg
received:REQUEST:0:4
Sending reply to Node-0 Msg
received:REQUEST:1:5 Sending
reply to Node-1 Msg
received:REPLY:2:OK Msg
received:REPLY:2:OK
Node-2 entered Critical Section @ 2022-05-04 22:58:58.585 Node-
2 exited Critical Section @ 2022-05-04 22:59:00.597 Completed

C:\Users\voras\Desktop>

Conclusion:
In this experiment, we developed algorithms for achieving both centralized and distributed mutual
exclusions which can be proved by the obtained results. The centralized algorithm was developed in
Java with the help of multi-threading and distributed mutual exclusion was achieved using nodes
system with one server using socket programming between nodes the on network.

Web Reference:

[1] https://github.com/trunc8/ricart-agrawala-algorithm

You might also like