Showing posts with label PL III Lab (PCDP Programs). Show all posts
Showing posts with label PL III Lab (PCDP Programs). Show all posts

Saturday, 14 March 2015

Implement a Parallel ODD-Even Sort algorithm using GPU or ARM equivalent or OPENMP

 Implement a Parallel ODD-Even Sort algorithm using GPU 

// oddeven.c
 #include<stdio.h>
#include<omp.h>

main()
{
  int A[25]={485,41,340,526,188,739,489,387,988,488};
  int N=10;
 
    int exch=1, start=0, i;
    int temp;
   printf("\n Array before Sorting-: ");
    for(i=0;i<=9;i++)
    {
      printf("\n %d",A[i]);
    }
    while(exch||start)
    {
      exch=0;
       #pragma omp parallel for private(temp) shared(start,exch)
      for(i=start;i<N-1;i+=2)
      {
         printf("\n%d=\t A[%d]= %d\tA[%d]= %d",i,i,A[i],i+1,A[i+1]);
        if(A[i]>A[i+1])
        {
          temp=A[i];
          A[i]=A[i+1];
          A[i+1]=temp;
          exch=1;
        }
      }
      if(start==0)
      {
        start=1;
      }
      else
      {
        start=0;
      }
    }
    printf("\n Sorted array is-: ");
    for(i=0;i<=9;i++)
    {
      printf("\n %d",A[i]);
    }
 }
test@test-ThinkCentre-M72e:~$ nvcc oddeven.c
test@test-ThinkCentre-M72e:~$ ./a.out

 Array before Sorting-:
 485
 41
 340
 526
 188
 739
 489
 387
 988
 488
0=     A[0]= 485    A[1]= 41
2=     A[2]= 340    A[3]= 526
4=     A[4]= 188    A[5]= 739
6=     A[6]= 489    A[7]= 387
8=     A[8]= 988    A[9]= 488
1=     A[1]= 485    A[2]= 340
3=     A[3]= 526    A[4]= 188
5=     A[5]= 739    A[6]= 387
7=     A[7]= 489    A[8]= 488
0=     A[0]= 41    A[1]= 340
2=     A[2]= 485    A[3]= 188
4=     A[4]= 526    A[5]= 387
6=     A[6]= 739    A[7]= 488
8=     A[8]= 489    A[9]= 988
1=     A[1]= 340    A[2]= 188
3=     A[3]= 485    A[4]= 387
5=     A[5]= 526    A[6]= 488
7=     A[7]= 739    A[8]= 489
0=     A[0]= 41    A[1]= 188
2=     A[2]= 340    A[3]= 387
4=     A[4]= 485    A[5]= 488
6=     A[6]= 526    A[7]= 489
8=     A[8]= 739    A[9]= 988
1=     A[1]= 188    A[2]= 340
3=     A[3]= 387    A[4]= 485
5=     A[5]= 488    A[6]= 489
7=     A[7]= 526    A[8]= 739
 Sorted array is-:
 41
 188
 340
 387
 485
 488
 489
 526
 739
 988test@test-ThinkCentre-M72e:~$


Implement concurrent prims algorithm using OPENMP

Implement concurrent prims algorithm using OPENMP

 //prims.c
// only able to send to 1 processor
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define DIM 1000

void initialization(void);
void delete_elements(int);

struct prim_data {
          int edges_weight[DIM][DIM];
         int dimension;
          int U[DIM];
          int total_min_distance;
          int count_nodes_in_mst;
        };

struct prim_data prim;

int main()
{
    int ch,j,t,p_c,p_j,k,serial=1;
    //int **prim.edges_weight[][]
    int i;

    //variable that holds the current maximum distance
    int min_distance;

   //variable that holds the next node in MST
    int new_next_element;

    prim.total_min_distance = 0;
    prim.count_nodes_in_mst = 0;

    //declaring the structs the are used by gettimeofday
    //struct timeval tb1;
    //struct timeval tb2;
    //setting the minimum distance
    min_distance = 1000;

    //opterr = 0;
    //parsing the arguments given

    printf("Enter the number of nodes:\n");
    scanf( "%d", &prim.dimension);
    printf("Enter the cost of edges: \n");

    for (i = 0; i < prim.dimension; ++i) {
        for (j = 0; j < prim.dimension; j++) {
            scanf("%d",&(prim.edges_weight[i][j]));
             printf("Cost: %d ",prim.edges_weight[i][j]);
              printf("From %d To %d\n",i,j);
        }
        //printf("\n");
    }


    printf("\nPrinting the weight array...\n\n");

    #pragma omp parallel default(none),private(i,j),shared(prim)
    {
    int tid = omp_get_thread_num();
    printf("thread %d starting\n",tid);
    #pragma omp for
    for(i=0; i<prim.dimension; i++){
        for(j=0; j<prim.dimension; j++) {
            printf("%d\t\n",prim.edges_weight[i][j]);
        }
       }
       //printf("\n");
    }

    //initializing the data
        initialization();

    //calculating for all the nodes
    for(k = 0; k < prim.dimension -1; k++)
    {
        min_distance = 1000;
        //for every node in minimum spanning tree
        for(i = 0; i < prim.count_nodes_in_mst; i++)
        {
            //declaring OpenMP's derective with the appropriate scheduling...
            #pragma omp parallel for
                for(j = 0; j < prim.dimension; j++)
                {
                //find the minimum weight
                    if(prim.edges_weight[prim.U[i]][j] > min_distance || prim.edges_weight[prim.U[i]][j]==0)
                    {
                        continue;
                    }
                    else
                    {
                    #pragma omp critical
                       {
                        min_distance = prim.edges_weight[prim.U[i]][j];
                        new_next_element = j;
                        }
                    }
                }
         }
        //Adding the local min_distance to the total_min_distance
        prim.total_min_distance += min_distance;
        //Adding the next node in the U set
        prim.U[i] = new_next_element;
        //Substructing the elements of the column in which  the new node is assosiated with
        delete_elements( new_next_element );
        //Increasing the nodes that they are in the MST
        prim.count_nodes_in_mst++;
    }

    printf("\n");
    //Print all the nodes in MST in the way that they stored in the U set
    for(i = 0 ; i < prim.dimension; i++) {
        printf("%d ",prim.U[i] + 1);
        if( i < prim.dimension - 1 ) printf("-> ");
      }

      printf("\n\n");
      printf("Total minimun distance: %d\n\n", prim.total_min_distance);
      printf("\nProgram terminates now..\n");
      return 0;
}

void initialization(void) {

    int i,j;

    prim.total_min_distance = 0;
    prim.count_nodes_in_mst = 0;

    //initializing the U set
    for(i = 0; i < prim.dimension; i++) prim.U[i] = -1;

    //storing the first node into the U set
    prim.U[0] = 0;
    //deleting the first node
    delete_elements( prim.U[0] );
    //incrementing by one the number of node that are inside the U set
    prim.count_nodes_in_mst++;
}

void delete_elements(int next_element) {

  int k;
  for(k = 0; k < prim.dimension; k++) {
    prim.edges_weight[k][next_element] = 0;
  }
}
--------------------------------------------------O/P------------------------------------------------------
test@test-ThinkCentre-M72e:~$ gcc prims.c -fopenmp
test@test-ThinkCentre-M72e:~$ ./a.out
Enter the number of nodes:
3
Enter the cost of edges:
2
Cost: 2 From 0 To 0
4
Cost: 4 From 0 To 1
5
Cost: 5 From 0 To 2
3
Cost: 3 From 1 To 0
7
Cost: 7 From 1 To 1
4
Cost: 4 From 1 To 2
5
Cost: 5 From 2 To 0
9
Cost: 9 From 2 To 1
5
Cost: 5 From 2 To 2

Printing the weight array...

thread 2 starting
5   
9   
5   
thread 3 starting
thread 0 starting
2   
4   
5   
thread 1 starting
3   
7   
4   

1 -> 2 -> 3

Total minimun distance: 8


Program terminates now..
test@test-ThinkCentre-M72e:~$

Implement a Multi-threading application for echo server using socket programming in JAVA

//Implement a Multi-threading application for echo server using socket programming in JAVA

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

public class Client {
    public static void main(String[] args) {
   
    String hostname = "localhost";
    int port = 6789;

    // declaration section:
    // clientSocket: our client socket
    // os: output stream
    // is: input stream
   
        Socket clientSocket = null; 
        DataOutputStream os = null;
        BufferedReader is = null;
   
    // Initialization section:
    // Try to open a socket on the given port
    // Try to open input and output streams
   
        try {
            clientSocket = new Socket(hostname, port);
            os = new DataOutputStream(clientSocket.getOutputStream());
            is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + hostname);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + hostname);
        }
   
    // If everything has been initialized then we want to write some data
    // to the socket we have opened a connection to on the given port
   
    if (clientSocket == null || os == null || is == null) {
        System.err.println( "Something is wrong. One variable is null." );
        return;
    }

    try {
        while ( true ) {
        System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String keyboardInput = br.readLine();
        os.writeBytes( keyboardInput + "\n" );

        int n = Integer.parseInt( keyboardInput );
        if ( n == 0 || n == -1 ) {
            break;
        }
       
        String responseLine = is.readLine();
        System.out.println("Server returns its square as: " + responseLine);
        }
       
        // clean up:
        // close the output stream
        // close the input stream
        // close the socket
       
        os.close();
        is.close();
        clientSocket.close();  
    } catch (UnknownHostException e) {
        System.err.println("Trying to connect to unknown host: " + e);
    } catch (IOException e) {
        System.err.println("IOException:  " + e);
    }
    }          
}

-------------------------------------------------------------------------------------------------------------------------
 //Server2.java
import java.io.*;
import java.net.*;

public class Server2 {
    public static void main(String args[]) {
    int port = 6789;
    Server2 server = new Server2( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server;
    // declare the number of connections

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int numConnections = 0;
    int port;
   
    public Server2( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)
   
        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }  
   
    System.out.println( "Server is started and is waiting for connections." );
    System.out.println( "With multi-threading, multiple connections are allowed." );
    System.out.println( "Any client can send -1 to stop the server." );

    // Whenever a connection is received, start a new thread to process the connection
    // and wait for the next connection.
   
    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        numConnections ++;
        Server2Connection oneconnection = new Server2Connection(clientSocket, numConnections, this);
        new Thread(oneconnection).start();
        }  
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server2Connection implements Runnable {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    int id;
    Server2 server;

    public Server2Connection(Socket clientSocket, int id, Server2 server) {
    this.clientSocket = clientSocket;
    this.id = id;
    this.server = server;
    System.out.println( "Connection " + id + " established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line + " from Connection " + id + "." );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n );
            }

        System.out.println( "Connection " + id + " closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}
---------------------------------------------------O/P-------------------------------------------------------------
test@test-ThinkCentre-M72e:~$ javac Client.java
test@test-ThinkCentre-M72e:~$ javac Client.java

test@test-ThinkCentre-M72e:~$ java Client
Enter an integer (0 to stop connection, -1 to stop server): 

test@test-ThinkCentre-M72e:~$ javac Server2.java
test@test-ThinkCentre-M72e:~$ java Server2
Server is started and is waiting for connections.
With multi-threading, multiple connections are allowed.
Any client can send -1 to stop the server.
Connection 1 established with: Socket[addr=/127.0.0.1,port=51452,localport=6789]


Implement Reader-Writer problem using OPENMP

// Implement Reader-Writer problem using OPENMP (file name rw.c)
#include<stdio.h>
#include<omp.h>

main()
{
 int semaphore=0;
#pragma omp parallel num_threads(2)  // two thread are created;
{
  int i;
int tid=omp_get_thread_num();
do
{
 printf("\n thread %d\n%d.read\n%d.write\n5.exit",tid,tid*2,tid*2+1);

//0: read at thread0 ;
//1: write at thread 0;
// 2: read at thread 1;
//3: write at thread 1;
//5: exit thread .;
scanf("%d",&i);

switch(i)
{
case 0: if(semaphore==1)//thread 1 is writing;
         {
            while(semaphore==1)//wait untill semaphore becomes 0;
              {
                  printf("\n shared data is in use");
                sleep(1);
              }
          }


         printf("\n reading in thread 0");
         sleep(5);
         printf("\n reading done in thread 0");
         break;

case 1: if(semaphore==1)// thread 1 is writing

           {
                 while(semaphore==1)// wait until smaphore become 0
                 sleep(1);
          }
      

 semaphore=1;
printf("\n writing in thread 0");
sleep(5);
printf("\n writing done in thread 0");
semaphore=0;
break;


case 2:  if(semaphore==1)//thread 0 is writing
         {
            while(semaphore==1)//wait untill semaphore becomes 0
              {
                  printf("\n shared data is in use");
                sleep(1);
              }
          }

printf("\n reading in thread 1");
sleep(5);
printf("reading done in thread 1");
break;


case 3:  if(semaphore==1)//thread 0 is writing
         {
            while(semaphore==1)//wait untill semaphore becomes 0
              {
                  printf("\n shared data is in use");
                sleep(1);
              }
          }
    semaphore=1;

    printf("\n writing  in thread 1");
    sleep(5);
     printf("writing  done in thread 1");
    semaphore=0;

    break;
     }
     }
while(i<5);
}
}

-------------------------------------------------O/P--------------------------------------------------------------
test@test-ThinkCentre-M72e:~$ gcc rw.c -fopenmp
test@test-ThinkCentre-M72e:~$ ./a.out

 thread 1
2.read
3.write
5.exit
 thread 0
0.read
1.write
2
5.exit
 reading in thread 1
reading done in thread 1
 thread 1
2.read
3.write
3
5.exit
 writing  in thread 1
writing  done in thread 1
 thread 0
0.read
1.write
1
5.exit
 writing in thread 0

 writing done in thread 0
 thread 1
2.read
3.write
5
5.exit


Tuesday, 10 March 2015

#include<stdio.h>

struct node
{
    unsigned dist[20];
    unsigned from[20];
}rt[10];
int main()
{
    int costmat[20][20];
    int nodes,i,j,k,count=0;
    printf("\nEnter the number of nodes : ");
    scanf("%d",&nodes);//Enter the nodes
    printf("\nEnter the cost matrix :\n");
    for(i=0;i<nodes;i++)
    {
        for(j=0;j<nodes;j++)
        {
            scanf("%d",&costmat[i][j]);
            costmat[i][i]=0;
            rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix
            rt[i].from[j]=j;
        }
    }
        do
        {
            count=0;
            for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance from the node i to k using the cost matrix
            //and add the distance from k to node j
            for(j=0;j<nodes;j++)
            for(k=0;k<nodes;k++)
                if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
                {//We calculate the minimum distance
                    rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
                    rt[i].from[j]=k;
                    count++;
                }
        }while(count!=0);
        for(i=0;i<nodes;i++)
        {
            printf("\n\n For router %d\n",i+1);
            for(j=0;j<nodes;j++)
            {
                printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
            }
        }
    printf("\n\n");
    return 0;
}
-------------------------------------------------------O/P-------------------------------------------------------------
computer@computer-OptiPlex-745:~$ gcc distance.c
computer@computer-OptiPlex-745:~$ ./a.out

Enter the number of nodes : 2

Enter the cost matrix :
3
1
2
3


 For router 1
   
node 1 via 1 Distance 0    
node 2 via 2 Distance 1

 For router 2
   
node 1 via 1 Distance 2    
node 2 via 2 Distance 0

Monday, 16 February 2015

PCDP(PL-III) NARAY SEARCH ALGORITHM

#include<stdio.h>
#include<omp.h>
//#include<timer.h>
int a[65536],s,test;
int global_size,global_x,n=4;

void nary_search(int,int);
void seq_search(int);
main()
{
    int i,size=65536,x=0;

    for(i=0;i<size;i++)
    a[i]=i*2;
    printf("Enter number to be searched\n");
    scanf("%d",&s);
    /*intf("enter the number of threads used\n");
    /*scanf("%d",&n)*/

    nary_search(size,x);



   
}



void nary_search(int size,int x)
{
    printf("size = %d\n",size);
    if(size<=4)
    {

        test=0;   
        #pragma omp parallel
        {
            int tid=omp_get_thread_num();
            if(a[global_x+tid]==s)
            {

                printf("found at %d\n",global_x+tid);
                test=1;
            }
        }
       
        if(test==0)
        {

            printf("not found\n");
        }
    }
    else
    {
        test=0;
        #pragma omp parallel 
        {
            int tid=omp_get_thread_num();
            printf("checking (%d --  %d)with thread %d on cpu %d \n",a[tid*size/n+x],a[tid*size/n+size/n-1+x],tid,sched_getcpu());   
            if(s>=a[tid*size/n+x] && s<=a[tid*size/n+size/n-1+x])
            {
                printf("may be here  %d ---- %d  size=(   %d   )\n",a[tid*size/n+x],a[tid*size/n+size/n-1+x],+size/n);
                global_size=size/n;               
                global_x=tid*global_size+x;
                test=1;
            }
        }
        if(test==1)
            nary_search(global_size,global_x);
        else
            printf("not found in");
    }
}
----------------------*-----------------------------*-------------------------------------------
O/p
file name save as omp_hello.c
and compile 
test@test-ThinkCentre-M72e:~$ gcc -o omp_helloc -fopenmp omp_hello.c
test@test-ThinkCentre-M72e:~$ ./omp_helloc
Enter number to be searched
4
size = 65536
checking (98304 --  131070)with thread 3 on cpu 0
checking (65536 --  98302)with thread 2 on cpu 3
checking (32768 --  65534)with thread 1 on cpu 2
checking (0 --  32766)with thread 0 on cpu 3
may be here  0 ---- 32766  size=(   16384   )
size = 16384
checking (24576 --  32766)with thread 3 on cpu 0
checking (8192 --  16382)with thread 1 on cpu 2
checking (16384 --  24574)with thread 2 on cpu 3
checking (0 --  8190)with thread 0 on cpu 1
may be here  0 ---- 8190  size=(   4096   )
size = 4096
checking (6144 --  8190)with thread 3 on cpu 0
checking (2048 --  4094)with thread 1 on cpu 2
checking (4096 --  6142)with thread 2 on cpu 3
checking (0 --  2046)with thread 0 on cpu 1
may be here  0 ---- 2046  size=(   1024   )
size = 1024
checking (1536 --  2046)with thread 3 on cpu 0
checking (1024 --  1534)with thread 2 on cpu 3
checking (512 --  1022)with thread 1 on cpu 2
checking (0 --  510)with thread 0 on cpu 1
may be here  0 ---- 510  size=(   256   )
size = 256
checking (256 --  382)with thread 2 on cpu 3
checking (384 --  510)with thread 3 on cpu 0
checking (128 --  254)with thread 1 on cpu 2
checking (0 --  126)with thread 0 on cpu 1
may be here  0 ---- 126  size=(   64   )
size = 64
checking (64 --  94)with thread 2 on cpu 3
checking (96 --  126)with thread 3 on cpu 0
checking (32 --  62)with thread 1 on cpu 2
checking (0 --  30)with thread 0 on cpu 1
may be here  0 ---- 30  size=(   16   )
size = 16
checking (16 --  22)with thread 2 on cpu 3
checking (8 --  14)with thread 1 on cpu 2
checking (24 --  30)with thread 3 on cpu 0
checking (0 --  6)with thread 0 on cpu 1
may be here  0 ---- 6  size=(   4   )
size = 4
found at 2