Wednesday, 18 March 2015

Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp

 Implement an calculator (64 bit Binary Multiplication) application using concurrent lisp

 

defvar a)
(defvar b)

(defvar c)
(defvar d)
(write-line " enter two numbers")
(setf a(read))
(setf b(read))
(sb-thread:make-thread(lambda()(progn(sleep 0)
(setf c(+ a b))
(print"addition")
(print c))))

(sb-thread:make-thread(lambda()(progn(sleep 0)
(setf c(- a b))
(print"Subtraction")
(print c))))


(sb-thread:make-thread(lambda()(progn(sleep 0)
(setf c(* a b))
(print"Multiplication ")
(print c))))


(sb-thread:make-thread(lambda()(progn(sleep 0)
(setf c(/ a b))
(print"Division")
(print c))))

---------------------------------------------O/P-------------------------------------------------------
pg@pg-17:~$ sbcl
This is SBCL 1.1.14.debian, an implementation of ANSI Common Lisp.
More information about SBCL is available at <http://www.sbcl.org/>.

SBCL is free software, provided as is, with absolutely no warranty.
It is mostly in the public domain; some portions are provided under
BSD-style licenses.  See the CREDITS and COPYING files in the
distribution for more information.
* (load "calci.lisp")
 enter two numbers
2347686465465
5675677667576

"addition"
8023364133041
"Subtraction"
-3327991202111
"Multiplication "
13324711642510134674262840
T
*
"Division"
       

Monday, 16 March 2015

Implement a Distributed matrix multiplication using CUDA / OpenMPI

Implement a Distributed matrix multiplication using CUDA / OpenMPI(PL-II Lab)

//Matrix Multiplication Program Using threading
#include <stdio.h>
#include <stdlib.h>
int Width=32;    //Width of matrix

int hTile_Width=300;
__device__ int dTile_Width=32; //Declare device copy for tile width

int CompareMatrix(int *M1,int *M2,int row,int col)
{        for(int i=0;i<(row*col);i++)
        {    if(M1[i]!=M2[i])
                return i;   
        }
        return -1;
       
}

/*Function to display Matrix elements
--------------------------------------------
Arguments
1-Matrix Pointer
2-Total elements size
--------------------------------------------
*/


void display_matrix(int *ptr,int m, int n)
{
    for(int i=0;i<m*n;i++)
    {    if(i%(n)==0){
            printf("\n");
        }
        printf("%d ",ptr[i]);
    }
}

/*Kernel function
---------------------------------------------
Arguments:
1-1st Matrix pointer
2-2nd Matrix pointer
3-Resultant matrix pointer
4-Width of square matrix
    This function calculates dot product of row and column for each thread
    __global__ qualifier indicates function can be called from host code and runs on device(GPU)
---------------------------------------------
*/
__global__ void MatrixMulKernel(int *Md,int *Nd,int *Pd,int w)
{
    int row=blockIdx.y*dTile_Width+ threadIdx.y;        //Get thread X position in a 2D block of threads
   int col=blockIdx.x*dTile_Width+ threadIdx.x;        //Get thread Y position in a 2D block of threads
   int Pvalue=0;
     if(row<w && col<w){
        for(int k=0;k<w;++k)    //
        {
        Pvalue+=Md[row*w+k]*Nd[k*w+col];        //Calculate sum of dot product of elements
        }
        Pd[row*w+col]=Pvalue;
    }   
}

void NormalMultiplication(int *M,int *N,int *P,int w)
{

    for(int i=0;i<w;++i){
        for(int j=0;j<w;j++){
            int sum=0;
            for(int k=0;k<w;k++){
                int a=M[i*w+k];
                int b=N[k*w+j];
                sum+=a*b;
            }
            P[i*w+j]=sum;
        }
    }

}

/*
-----------------------------------------------
Arguments
1-1st Matrix pointer
2-2nd Matrix pointer
3-Resultant matrix pointer
4-Width of square matrix
    This function copy matrix data from host memory to device global memory and invoke kernel
-----------------------------------------------
 */
void MatrixMultiplication(int *M,int *N,int *P,int w)
{    int *Md,*Nd,*Pd;        //Matrix Pointer on device memoryi.e GPU
    int size=w*w*sizeof(int*);
    int x;

    cudaMalloc((void**)&Md,size);        //Allocate memory on device global memory
    cudaMemcpy(Md,M,size,cudaMemcpyHostToDevice);    //Copy matrix data from host to device memory
    cudaMalloc((void**)&Nd,size);
    cudaMemcpy(Nd,N,size,cudaMemcpyHostToDevice);
    cudaMalloc((void**)&Pd,size);
   

            if(w%hTile_Width!=0)            //
            {
                x=w/hTile_Width+1;
            }
            else
            {
                x=w/hTile_Width;
            }
       
        dim3 dimGrid(x,x);                                    //Variable for threads arrangement in a block.
        dim3 dimBlock(hTile_Width,hTile_Width);        //Variable for blocks arrangement in a grid.   

    MatrixMulKernel<<<dimGrid,dimBlock>>>(Md,Nd,Pd,w);    //Kernel invocation with grid and block specification in angle brackets

    cudaMemcpy(P,Pd,size,cudaMemcpyDeviceToHost);    //Copy resultant matrix from device to host
    //Free device memory
    cudaFree(Md);
    cudaFree(Nd);
    cudaFree(Pd);

}

int main()
{
    int mat_size=Width*Width*sizeof(int*);    //Calculate memory size required for float matrix
    int tot_elements=Width*Width;
    int *M,*N,*P,*ptr,*P_CPU;    // Host matrix pointers
    int a=0;
    int i=0;

    M=(int*)malloc(mat_size);        //Allocate memory on host for matrix
    N=(int*)malloc(mat_size);
    P=(int*)malloc(mat_size);
    P_CPU=(int*)malloc(mat_size);
    ptr=M;
    printf("\nGenarating random elements for matrix");
    for(i=0;i<tot_elements;i++)
    {    a=(rand()%10);        //Generates random no. in 0 to 10 range
        *ptr=a;
        ptr++;
    }
    ptr=N;
    for(i=0;i<tot_elements;i++)
    {
        a=(rand()%10);
        *ptr=a;
        ptr++;
    }
    printf("\nMatrix generated");
    MatrixMultiplication(M,N,P,Width);
    printf("\nDone with GPU");
    display_matrix(N,Width,Width);
    printf("\nMatrix Multiplication (GPU) is :");
    display_matrix(P,Width,Width);
    NormalMultiplication(M,N,P_CPU,Width);
    printf("\nDone with CPU");   
    printf("\n\nMatrix Multiplication is :");
    display_matrix(P_CPU,Width,Width);

    if(CompareMatrix(P,P_CPU,Width,Width)==-1)
        printf("\n\nBoth matrix are same\n");
    else
    {    printf("\n\nBoth matrix are not same\n\n");
        //printf("%d",CompareMatrix(P,P_CPU,Width,Width));
    }
}

----------------------------------------------------O/P---------------------------------------------------

test@test-ThinkCentre-M72e:~$ nvcc Matrix.cu
test@test-ThinkCentre-M72e:~$ ./a.out

Genarating random elements for matrix
Matrix generated
Done with GPU
1 4 0 3 1 2 7 7 9 8 1 0 7 6 0 1 0 2 5 1 9 7 1 3 1 2 0 6 8 7 4 9
2 4 4 5 9 1 2 8 9 6 0 6 4 0 9 4 5 4 6 6 3 9 9 5 2 1 3 0 9 9 1 3
4 5 8 5 7 3 3 8 9 5 5 3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0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Done with CPU

Matrix Multiplication is :
710 585 753 595 677 651 688 735 686 591 462 686 720 505 674 578 517 666 656 656 808 700 667 655 383 515 588 497 828 715 633 614
646 572 661 648 718 711 726 635 690 579 421 618 676 509 668 584 493 637 605 521 745 634 589 602 434 511 542 525 729 750 629 551
807 705 677 689 779 713 814 858 771 639 540 674 799 507 722 657 647 765 677 693 909 787 662 669 458 563 697 673 823 876 663 697
676 552 704 661 609 758 776 684 650 480 444 780 689 535 693 592 513 730 540 622 855 568 660 680 490 518 624 455 787 637 548 583
864 650 751 675 756 856 858 751 816 686 498 798 865 570 757 771 695 787 698 771 932 681 858 794 614 522 623 535 905 759 691 614
786 700 690 734 697 760 788 771 775 617 554 712 813 530 683 582 615 762 690 705 920 749 588 745 444 600 661 628 834 832 681 678
819 667 772 719 789 832 782 832 798 617 443 764 804 595 658 682 503 845 626 697 956 685 684 662 464 605 638 638 870 790 685 700
700 573 647 533 667 640 738 686 686 592 419 600 782 519 638 553 500 607 586 592 840 560 531 636 440 538 511 556 652 704 625 546
689 514 619 515 585 568 615 609 637 570 388 562 603 370 588 615 554 535 521 619 713 525 538 519 372 532 565 490 619 654 475 474
747 619 632 727 806 798 822 799 864 634 521 644 752 655 692 674 588 786 667 694 897 704 783 765 554 575 641 631 858 770 735 640
620 473 551 454 481 657 640 499 656 505 322 538 655 392 535 515 442 552 544 585 743 586 580 528 423 466 472 488 727 489 482 547
688 531 704 663 665 761 755 719 624 511 412 692 728 529 720 574 511 746 563 538 845 630 613 673 484 522 588 535 731 731 597 594
823 600 664 671 791 777 798 734 780 529 471 761 746 486 712 683 618 808 564 679 804 747 735 618 497 498 667 535 830 732 619 587
811 622 787 716 793 735 848 775 857 683 453 815 828 590 656 630 478 829 703 692 927 703 692 747 433 581 583 571 914 815 787 662
847 702 760 775 804 842 812 767 898 667 557 820 757 596 899 736 681 754 612 744 844 774 740 777 601 616 740 678 866 826 640 702
649 498 663 536 610 605 629 604 716 573 398 634 643 380 473 544 469 619 545 632 770 543 673 513 350 440 554 570 657 628 541 526
652 621 609 603 663 807 771 664 684 570 418 582 622 499 665 626 503 618 601 522 821 676 599 590 466 576 628 683 819 714 540 591
754 551 607 761 742 778 772 758 791 606 479 664 646 535 743 739 657 780 640 682 814 805 792 705 574 569 731 648 877 763 687 645
954 684 798 813 844 905 831 830 843 739 600 813 844 604 953 833 710 817 725 738 956 874 860 780 619 699 752 663 931 850 671 754
568 490 511 554 519 540 532 573 590 425 363 565 526 408 561 463 462 545 442 467 576 542 390 485 336 433 522 484 569 651 458 494
770 536 629 748 602 818 761 643 770 564 459 573 701 552 653 684 617 741 564 684 899 605 637 643 571 611 677 609 741 695 638 609
676 557 678 651 679 692 691 644 664 514 481 665 544 451 678 608 535 681 598 635 759 633 750 600 523 426 627 573 727 671 555 560
642 489 485 511 571 596 578 617 606 618 441 558 729 417 617 604 563 558 572 613 703 595 643 545 447 471 474 456 651 586 543 491
629 518 653 548 637 566 633 645 676 593 378 601 644 392 580 544 457 600 651 603 799 686 673 593 361 428 521 595 713 761 610 603
634 535 596 510 546 625 605 579 599 468 298 506 587 430 485 515 509 633 501 586 662 519 550 579 403 396 487 477 657 605 483 567
768 630 656 642 696 776 748 730 766 513 506 623 674 463 691 651 677 679 615 697 829 739 672 650 489 557 740 611 776 714 559 641
699 555 613 628 665 773 689 735 857 661 385 601 731 446 691 696 613 643 555 703 853 708 714 579 523 568 636 609 798 695 484 642
620 509 555 625 587 615 613 599 654 430 360 558 574 406 578 527 541 616 506 531 636 590 530 545 399 481 548 489 674 660 500 585
703 497 575 600 559 564 580 617 596 506 435 543 679 426 583 473 516 688 579 565 692 535 579 559 404 435 478 466 626 622 554 559
800 606 630 663 722 767 788 668 805 558 529 708 805 530 778 644 624 699 599 632 846 705 717 673 494 563 662 564 795 777 602 606
956 656 792 733 829 837 850 763 886 666 533 767 873 642 846 756 687 854 715 789 957 792 849 742 592 623 706 658 865 800 742 685
593 493 531 534 612 607 665 579 630 551 380 535 649 447 612 592 545 515 523 520 654 577 551 559 422 510 506 446 646 624 540 498

Both matrix are not same

test@test-ThinkCentre-M72e:~$

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