You are on page 1of 17

CONTENTS

1. Design, develop and execute a program using any thread library to create the number of threads specified by the user; each thread independently generates a random integer as an upper limit, and then computes and prints the number of primes less than or equal to that upper limit along with that upper limit.

2. Rewrite above program such that the processes instead of threads are created and the number of child processes created is fixed as two. The program should make use of kernel timer to measure and print the real time, processor time, user space time and kernel space time for each process.

3. Design, develop and implement a process with a producer thread and a consumer thread which make use of a bounded buffer (size can be prefixed at a suitable value) for communication. Use any suitable synchronization construct.

4. Design, develop, and execute a program to solve a system of n linear equations using Successive Over-relaxation method and n processes which use Shared Memory API.

5. Design, develop, and execute a program to demonstrate the use of RPC.

Experiment 1
Design, develop and execute a program using any thread library to create the number of threads specified by the user; each thread independently generates a random integer as an upper limit, and then computes and prints the number of primes less than or equal to that upper limit along with that upper limit. import java.util.Random; import java.io.*; public class Primenumber { public static void main(String args[]) { try { int number=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter the number of threads to be created \n"); number=Integer.parseInt(br.readLine()); for(int index=0;index<number;index++) { Primeno P=new Primeno(); P.primenum(); } }catch(Exception e){} } } class Primeno extends Thread { void primenum() { start(); } public void run(){ Random randomGenerator=new Random(); int randomInt=randomGenerator.nextInt(20); //String name=Primeno.currentThread(); System.out.println("the current thread in execution is"+Primeno.currentThread()); System.out.println("The upperlimit of"+Primeno.currentThread()+ "prime no is"+randomInt); for(int index=2;index<randomInt;index++) { if(isPrime(index)) System.out.println("ThreadName:"+Primeno.currentThread().getName()+" "+index); Try

{ sleep(1000); } catch(InterruptedException e){ System.out.println(e); } }//end of for loop }//end of run method public boolean isPrime(int num) { boolean prime=true; int limit=(int)Math.sqrt(num); for(int index=2;index<=limit;index++) { if(num%index==0){ prime=false; break; } } return prime; } }//end of thread prime number

Output
enter the number of threads to be created 4 the current thread in execution isThread[Thread-0,5,main] The upperlimit ofThread[Thread-0,5,main]prime no is7 ThreadName:Thread-0 2 the current thread in execution isThread[Thread-2,5,main] The upperlimit ofThread[Thread-2,5,main]prime no is8 ThreadName:Thread-2 2 the current thread in execution isThread[Thread-3,5,main] The upperlimit ofThread[Thread-3,5,main]prime no is15 ThreadName:Thread-3 2 the current thread in execution isThread[Thread-1,5,main] The upperlimit ofThread[Thread-1,5,main]prime no is14 ThreadName:Thread-1 2 ThreadName:Thread-0 3 ThreadName:Thread-3 3 ThreadName:Thread-1 3

ThreadName:Thread-2 3 ThreadName:Thread-3 5 ThreadName:Thread-0 5 ThreadName:Thread-2 5 ThreadName:Thread-1 5 ThreadName:Thread-3 7 ThreadName:Thread-1 7 ThreadName:Thread-2 7 ThreadName:Thread-3 11 ThreadName:Thread-1 11 ThreadName:Thread-3 13 ThreadName:Thread-1 13

Experiment 2
Rewrite above program such that the processes instead of threads are created and the number of child processes created is fixed as two. The program should make use of kernel timer to measure and print the real time, processor time, user space time and kernel space time for each process.

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <sys/times.h> child_process(int process_No) { int i,n,prime, TotPrimeNo=0; struct tms cp_t1, cp_t2; long rcpt1, rcpt2; int Rand; rcpt1 = times(&cp_t1); printf("\n Processor time for child process (%d) = %d", (process_No +1), rcpt1); printf("\n Created child process %d ", process_No+1); srand(process_No); Rand = random() % 1000000; printf(" \n Random number = %d\t", Rand ); for(n=0; n<Rand; n++) { prime = 1; for(i=2; i<n; i++) { if(n%i == 0) { prime = 0; break; } } if(prime) { //printf(" \n Prime number[%d]\t= %d", TotPrimeNo, n ); TotPrimeNo++; } }

printf("\nTotal Prime Nos=%d\n",TotPrimeNo); rcpt2 = times(&cp_t2); printf("\n Real time for child process (%d) = %d", (process_No +1), (rcpt2-rcpt1)); printf("\n User space time for child process(%d) = %d", (process_No +1), (cp_t2.tms_cutimep_t1.tms_cutime)); printf("\n kernel space time for child process(%d) = %d\n\n", (process_No +1), (cp_t2.tms_cstime-cp_t1.tms_cstime)); exit(0); } void CreateProcess() { int i; for (i=0; i<2;i++) { if(fork() == 0) child_process(i); } for (i=0; i<2;i++) { wait(); } } int main () { long p_mt1, p_mt2; struct tms p_mst1, p_mst2; p_mt1 = times(&p_mst1); CreateProcess(); p_mt2 = times(&p_mst2); printf("\n Real time for parent process = %d", p_mt2-p_mt1); printf("\n User space time for parent process = %d", (p_mst2.tms_utime-p_mst1.tms_utime)); printf("\n Kernel space time for parent process = %d\n\n", (p_mst2.tms_stime-p_mst1.tms_stime)); }

Output
Processor time for child process (1) = 18847897 Created child process 1

Processor time for child process (2) = 18847897 Created child process 2 Random number = 289383 Total Prime Nos=25180 Real time for child process (2) = 1402 User space time for child process(2) = 0 kernel space time for child process(2) = 0 Random number = 289383 Total Prime Nos=25180 Real time for child process (1) = 1422 User space time for child process(1) = 0 kernel space time for child process(1) = 0

Real time for parent process = 1422 User space time for parent process = 0 Kernel space time for parent process = 0

Experiment 3
Design, develop and implement a process with a producer thread and a consumer thread which make use of a bounded buffer (size can be prefixed at a suitable value) for communication. Use any suitable synchronization construct. import java.util.*; public class BoundedBuffer { public static final int NAP_TIME = 5; private static final int BUFFER_SIZE = 3; private volatile int count; private int in; // points to the next free position in the buffer private int out; // points to the next full position in the buffer private Object[] buffer; public BoundedBuffer(){ // buffer is initially empty count = 0; in = 0; out = 0; buffer = new Object[BUFFER_SIZE]; } // producer calls this method public synchronized void enter(Object item) throws InterruptedException { if (count == BUFFER_SIZE) { wait() ; // Buffer is full and wait for consumer to consume. }else{ // add an item to the buffer ++count; buffer[in] = item; in = (in + 1) % BUFFER_SIZE; if (count == BUFFER_SIZE) System.out.println("Producer Entered " + item + " Buffer FULL"); else System.out.println("Producer Entered " + item + " Buffer Size = " + count); notifyAll(); } } // consumer calls this method public synchronized Object remove() throws InterruptedException { Object item = null; if (count == 0) {

wait(); // Buffer is empty and wait for producer to produce. }else{ // remove an item from the buffer --count; item = buffer[out]; out = (out + 1) % BUFFER_SIZE; if (count == 0){ System.out.println("Consumer Consumed " + item + " Buffer EMPTY"); }else{ System.out.println("Consumer Consumed " + item + " Buffer Size = " + count); } notifyAll(); } return item; } }

//**** Producer.java *********//


/ * This is the producer thread for the bounded buffer problem. */ import java.util.*; public class Producer extends Thread { private BoundedBuffer buffer; public Producer(BoundedBuffer b) { buffer = b; } public void run() { Date message; While (true) { int sleeptime = (int) (BoundedBuffer.NAP_TIME * Math.random() ); try { System.out.println("Producer sleeping for " + sleeptime + " seconds"); sleep(sleeptime*1000); // produce an item & enter it into the buffer message = new Date(); System.out.println("Producer produced " + message); buffer.enter(message); }catch(InterruptedException e) { } } }

//**** Server.java ****//


/** This creates the buffer and and creates producer and consumer threads by passing the referance of the created buffer objects. **/ public class Server { public static void main(String args[]) { BoundedBuffer server = new BoundedBuffer(); // now create the producer and consumer threads Producer producerThread = new Producer(server); Consumer consumerThread = new Consumer(server); producerThread.start(); consumerThread.start(); } }

Output
Producer sleeping for 3 seconds Consumer sleeping for 2 seconds Consumer wants to consume. Producer produced Sun Nov 07 13:03:00 IST 2010 Producer Entered Sun Nov 07 13:03:00 IST 2010 Buffer Size = 1 Producer sleeping for 0 seconds Consumer sleeping for 1 seconds Producer produced Sun Nov 07 13:03:00 IST 2010 Producer Entered Sun Nov 07 13:03:00 IST 2010 Buffer Size = 2 Producer sleeping for 4 seconds Consumer wants to consume. Consumer Consumed Sun Nov 07 13:03:00 IST 2010 Buffer Size = 1 Consumer sleeping for 0 seconds Consumer wants to consume. Consumer Consumed Sun Nov 07 13:03:00 IST 2010 Buffer EMPTY Consumer sleeping for 4 seconds Producer produced Sun Nov 07 13:03:04 IST 2010 Producer Entered Sun Nov 07 13:03:04 IST 2010 Buffer Size = 1 Producer sleeping for 3 seconds Consumer wants to consume. Consumer Consumed Sun Nov 07 13:03:04 IST 2010 Buffer EMPTY Consumer sleeping for 4 seconds

Experiment 4
Design, develop, and execute a program to solve a system of n linear equations using Successive Over-relaxation method and n processes which use Shared Memory API. #include<stdio.h> #include<stdlib.h> #include<math.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #define A(x,y) A[(u+1)*(x)+y] #define PRECISION 0.0001 int u; int is_converged(int n, float *A, float *B, float *p) { float *sum; int i,j; sum=(float *)malloc(n*sizeof(float)); for(i=0;i<n;++i) sum[i]=0; for(i=0;i < n;++i) { for(j=0; j < n;++j) sum[i] += A(i,j)*p[j]; sum[i]=fabs(B[i]-sum[i]); } for(i=0;i<n;++i) { /* not converged if any result is off by more than PRECISION */ if(sum[i]>PRECISION) return 0; } return 1; }

/* Does one SOR iteration */


void SOR(int n, float *A, float *B, float *p, float w) { float sum; int i,j; for(i=0;i < n; ++i) { sum=0; for(j=0;j < i;++j) { sum += A(i,j)* p[j];

} for (j = i+1;j < n; ++j) { sum += A(i,j) * p[j]; } p[i] += w * ( ((B[i]-sum)/A(i,i)) - p[i]); } }

//Main//
int main(int argc, char* argv[]) { float *A,*p,*B; float w; int shmid; key_t key; int i,j; printf("\nPlease input the number of lines:"); scanf("%d",&u); A=(float *)calloc(u*(u+1),sizeof(float)); B=(float *)malloc(u*sizeof(float)); printf("Please input the matrix A(%dx%d):\n", u, u); //n*n for(i = 1; i <= u; ++i) { printf("\nPlease input line %d:",i); for(j=1;j<=u;++j) scanf("%f",&A(i-1,j-1)); } printf("\nPlease input matrix B(1x%d):",u); for(i=0;i<u;++i) scanf("%f",&B[i]);

/* shared memory key */


key = 5678; /* Create the shared memory segment for storing the results of SOR * iterations. */ if ((shmid = shmget(key, sizeof (float) * u, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } /* Now we attach the segment to our data space. */ if ((p = (float *) shmat(shmid, NULL, 0)) == (float *) -1) { perror("shmat");

exit(1); } /* Read the starting guess values to the shared memory. This will be * used by the child process computing first SOR iteration */ printf("\nPlease input the start guess (1x%d): ",u); for(i=0;i < u; ++i) scanf("%f",&p[i]); printf("\nPlease input the relax VAR(w): "); // scanf("%f",&w); while (!is_converged(u, A, B, p)) { if (fork() == 0) { /* Do the SOR iterations in the child process, write the iteration * result in shared memory */ if ((shmid = shmget(key, sizeof (float) * u, 0666)) < 0) { perror("shmget"); exit(1); } /* Now we attach the segment to our data space. */ if ((p = (float *) shmat(shmid, NULL, 0)) == (float *) -1) { perror("shmat"); exit(1); } /* perform one iteration using the child process */ SOR(u, A, B, p, w); exit(0); } wait(); } printf("The SOR solution:\n"); for(i=0; i < u;++i) printf("x[%d]=%f \n", i+1, p[i]); return 0; }

Output
Please input the number of lines:2 Please input the matrix A(2x2): Please input line 1:2 3

Please input line 2:4 9 Please input matrix B(1x2):6 15 Please input the start guess (1x2):1 1 Please input the relax VAR(w):1.5 The SOR solution: x[1]=1.500061 x[2]=0.999980 ------------------------------------------Please input the number of lines:2 Please input the matrix A(2x2): Please input line 1:16 3 Please input line 2:7 -11 Please input matrix B(1x2):11 13 Please input the start guess (1x2):1 1 Please input the relax VAR(w):1 The SOR solution: x[1]=0.812182 x[2]=-0.664975

Experiment 5
Design, develop, and execute a program to demonstrate the use of RPC. //**SERVER PROGRAM**// import org.apache.xmlrpc.server.PropertyHandlerMapping; import org.apache.xmlrpc.webserver.WebServer; public class RpcServer { public Integer sum(int x, int y) { System.out.println("Finding sum for " + x + " and " + y); return new Integer(x + y); } public static void main(String[] args) { try { System.out.println("Attempting to start XML-RPC Server..."); WebServer server = new WebServer(8080); PropertyHandlerMapping phm = new PropertyHandlerMapping(); phm.addHandler("math", RpcServer.class); server.getXmlRpcServer().setHandlerMapping(phm); server.start(); System.out.println("Started successfully."); System.out.println("Accepting requests. (Halt program to stop.)"); } catch (Exception exception) { System.err.println("JavaServer: " + exception); } } } //**CLIENT PROGRAM**// import java.net.URL; import java.util.Vector; import org.apache.xmlrpc.client.XmlRpcClient; import org.apache.xmlrpc.client.XmlRpcClientConfigImpl; public class RpcClient { public static void main(String[] args) throws Exception { XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();

String serverAddress = "localhost:8080"; int val1 = 0; int val2 = 0; if (args.length > 0) { serverAddress = args[0]; } if (args.length >= 2) { val1 = Integer.parseInt(args[1]); val2 = Integer.parseInt(args[2]); } config.setServerURL(new URL("http://" + serverAddress + "/RPC2")); XmlRpcClient server = new XmlRpcClient(); server.setConfig(config); Vector<Integer> params = new Vector<Integer>(); params.addElement(new Integer(val1)); params.addElement(new Integer(val2)); Object result = server.execute("math.sum", params); int sum = ((Integer) result).intValue(); System.out.println("The sum is: " + sum); } }

Output
Server: -----Attempting to start XML-RPC Server... Started successfully. Accepting requests. (Halt program to stop.) Finding sum for 17 and 13 Finding sum for 54 and 23 Client: ------$ java RpcClient localhost:8080 17 13 The sum is: 30 $ java RpcClient localhost:8080 54 23 The sum is: 77

You might also like