Question

Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread"...

Please change this 2 thread program to a 4 thread program.

/*compile as "gcc thread.c -pthread" */
#include <pthread.h>
#include <stdio.h>
#include <time.h>

#define SIZE 100000000 //100 M
//#define SIZE 10000
#define NUMBER_OF_TIMES 100

float a[SIZE];

typedef struct {
       int start;
       int end;
       double sum;
       int pid;
   } range;

void *thread_function(void *arg) //define a function that will be executed from
//within a thread
{
   range *incoming = (range *) arg;
   int i, j;
   double sum;
   int start, end, pid;

   start = incoming->start;
   end = incoming->end;
   pid = incoming->pid;

//   printf ("Array entries (start, end) = (%d, %d)\n", start,end);

   if(pid != 0)
   {
       printf("2T: PID %d started: time = %f\n", pid, (double) time(NULL));
   }

   sum = 0;
   for(j = 0; j <NUMBER_OF_TIMES; j++)
       for (i=start; i<end; i++)
           sum=sum + a[i];

//   printf("Pid = %d: sum = %f\n", pid, sum);
   incoming->sum = sum;   //save the result from the PE

   if(pid != 1)
   {
       printf("2T: PID %d ended: time = %f\n", pid, (double) time(NULL));
   }
   return NULL;
}

int main (void)
{
   pthread_t threadID;
   void *exit_status;
   range one;
   range two;
   int i;
   double sum;


   for (i=0; i<SIZE; i++) //initialize array
       a[i] = 1;

   printf("2T: PID 0 started: time = %f\n", (double) time(NULL));

   //create a thread that calls thread_function, and pass the indeces
//for the 1st half of the array
    one.start = 0;
   one.end = SIZE/2-1;
   one.pid = 1; //PE is 1
   pthread_create(&threadID, NULL, thread_function, &one); //create a thread and run thread_function

   //main will become the 2nd thread and will call thread_function
//Pass the indeces to the 2nd half of the array
two.start = SIZE/2;   //main computes the sum for the second half of the array elements
   two.end = SIZE;
   two.pid = 0;
   thread_function(&two);

   pthread_join(threadID, &exit_status); //wait for the 1st thread to end
   sum = one.sum + two.sum; //PE 2 combines the two partial sums

   printf("2T: PID 0 ended: time = %f\n", (double) time(NULL));

   printf("2T: Final sum = %e\n", sum);
  
   two.start = SIZE/2;   //main computes the sum for the second half of the array elements
   two.end = SIZE;
   two.pid = 0;
   thread_function(&two);

   pthread_join(threadID, &exit_status); //wait for the 1st thread to end
   sum = one.sum + two.sum; //PE 2 combines the two partial sums

   printf("2T: PID 0 ended: time = %f\n", (double) time(NULL));

   printf("2T: Final sum = %e\n", sum);

   return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I have created not only for 4 threads but for N number of threads although you can set a limit to how many threads user can enter using MAX_THREADS .

HOPE THIS HELPS ...

/*compile as "gcc thread.c -pthread" */
#include <pthread.h>
#include <stdio.h>
#include <time.h>

#define SIZE 100000000 //100 M
//#define SIZE 10000
#define MAX_THREADS 10
#define NUMBER_OF_TIMES 100

float a[SIZE];

typedef struct {
int start;
int end;
double sum;
int pid;
} range;

void *thread_function(void *arg) //define a function that will be executed from
//within a thread
{
range *incoming = (range *) arg;
int i, j;
double sum;
int start, end, pid;

start = incoming->start;
end = incoming->end;
pid = incoming->pid;

printf ("Array entries (start, end) = (%d, %d)\n", start,end);

if(pid != 0)
{
printf("2T: PID %d started: time = %f\n", pid, (double) time(NULL));
}

sum = 0;
for(j = 0; j <NUMBER_OF_TIMES; j++)
{
for (i=start; i<end; i++)
{
sum=sum + a[i];
}
  
}
// printf("Pid = %d: sum = %f\n", pid, sum);
incoming->sum = sum; //save the result from the PE

if(pid != 1)
{
printf("2T: PID %d ended: time = %f\n", pid, (double) time(NULL));
}
return NULL;
}

int main (void)
{
pthread_t threadID;
void *exit_status;
range one;
range two;
int i;
double sum;
int noOfThreads, result , chunk;
range threads[MAX_THREADS];

for (i=0; i<SIZE; i++) //initialize array
a[i] = 1;

// printf("2T: PID 0 started: time = %f\n", (double) time(NULL));
printf("how many threads do you want ? \t");
scanf("%d",&noOfThreads);

  if(noOfThreads > MAX_THREADS)
{
printf("My CPU does not have this many threads\nPlease enter again ....\nThreads you want : ");
scanf("%d",&noOfThreads);
}

//if we are using N no of threads we need to divide the array into equal chunks ...
chunks = SIZE/noOfThreads ;
// loop to initialize all the threads with values and call thread_function
for(i=0 ; i<noOfThreads ; i++)
{
threads[i].start = (i*chunk)+1;
threads[i].end = (threads[i].start + chunk)-1 ;
threads[i].pid = i+1 ;
pthread_create(&threadID, NULL , thread_function, &threads[i])

}

for(i=0 ; i<noOfThreads ; i++)
{
pthread_join(threadID, &exit_status); //wait for the 1st thread to end
}

for(i=0 ; i<noOfThreads ; i++)
{
sum = sum + threads[i].sum;
}

printf("2T: PID 0 ended: time = %f\n", (double) time(NULL));

printf("2T: Final sum = %e\n", sum);

return 0;
}

Add a comment
Know the answer?
Add Answer to:
Please change this 2 thread program to a 4 thread program. /*compile as "gcc thread.c -pthread"...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Compile and run the deadlockFree.c program below and report if this program does go into deadlock...

    Compile and run the deadlockFree.c program below and report if this program does go into deadlock or not. Modify this deadlockFree.c program so that you change the lock/unlock order of the mutexes. Experiment with the order of locks (and maybe extend the number of loop iterations) until you find a scenario where you can demonstrate deadlock. //Program: deadlockFree.c A simple threaded program to demonstrate the deadlock condition.Two threads are used to wait on two MUTEXES. Careful ordering of locks should...

  • Pleas help I need to create and array to add to my code something like this...

    Pleas help I need to create and array to add to my code something like this for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; ::::::::: CODE ::::::::::::: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>    int sharedVar = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* thread handler */ void *threadHandler(void *vargp) {    int i = 0;    pthread_mutex_lock(&mutex);   ...

  • How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses...

    How do I do this C++ in a Unix Environment assignment Given dot1m.c 1. The program (dot1m.c) uses mutex to lock and unlock the shared resource (dotstr.sum) for access control as shown below. pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\n", offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); 2. Modify dot1m.c program to use reader-writer lock (instead of mutex).      Replace the codes (for mutex) by the codes (for reader-writer lock).            To initialize reader-writer lock, pthread_rwlock_initializer.            At the end,...

  • In C using the following 2 files to create a 3rd file that uses multiple threads...

    In C using the following 2 files to create a 3rd file that uses multiple threads to improve performance. Split the array into pieces and each piece is handled by a different thread. Use 8 threads. run and compile in linux. #include <stdio.h> #include <sys/time.h> #define BUFFER_SIZE 4000000 int countPrime=0; int numbers[BUFFER_SIZE]; int isPrime(int n) { int i; for(i=2;i<n;i++) if (n%i==0) return 0; return 1; } int main() { int i; // fill the buffer for(i=0;i<BUFFER_SIZE;i++) numbers[i] = (i+100)%100000; //...

  • C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) L...

    C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) Last Name (char[]) Age (int) Height in Inches (double) Weight in Pounds (double) You will use pass-by-reference to modify the values of the arguments passed in from the main(). Remember that arrays require no special notation, as they are passed by reference automatically, but the other...

  • Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By...

    Please finish the following program /** * Basic POSIX Thread (pthread) Usage 1. * * By walking through this example you’ll learn: * - How to use pthread_create(). * - How to use pthread_exit(). * - How to use pthread_join(). * */ #include <stdio.h> #include <unistd.h> #include <pthread.h> #include <sys/wait.h> void* ninja(void* arg){ printf("Who’s there?"); fflush(stdout); pthread_exit("ninja"); } // // Expected output: // // Knock knock. // Who's there? - from ninja // Knuc...kles. // int main(int argc, char* argv[]){...

  • a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems....

    a multi-threaded producer / consumer program without any locking or signaling. It therefore has synchronization problems. Add locks and signals so that it works correctly. /* Homework 5.X */ /* Robin Ehrlich */ /* compile: gcc Homework5.c -lpthread */ #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct class {    struct class *next;    int id;    int grade; }; #define SLEEP_TIME 1 #define MAX_PRODUCE 10 static struct class *classHead = NULL; static struct class *classTail = NULL; static...

  • Please explain your answers thoroughly for the following question. 1) Compile thread2.c (remember the -lpthread flag)....

    Please explain your answers thoroughly for the following question. 1) Compile thread2.c (remember the -lpthread flag). Run it numerous times, and notice the output usually differs. a) Why is the variable myglobal usually not 40? Be specific, be precise. b) In what special case would myglobal be 40? Be specific, be precise. #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> /* Purpose: Use 2 threads to increment myglobal exactly 40 times in total. Compile: using -pthread option */...

  • so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n)...

    so in this code, it computes the sum 1+2+....+n but i want it to compute 2*(1+2+....+n) using semaphores implement solution to the critical section problem #include #include int sum; /* this data is shared by the thread(s) */ void *runner(void *param); /* threads call this function */ int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of thread attributes */ if (argc != 2) { fprintf(stderr,"usage: a.out \n"); return -1; } if...

  • Program 2: Thread version int i = 100; char *buffer: void *tfuc(void *noarg) { int j...

    Program 2: Thread version int i = 100; char *buffer: void *tfuc(void *noarg) { int j = 0; printf("B:1-%d, j = %d\n",1,1); printf("B: I = %d, j = %d\n",1,1); j = 3; strcpy(buffer, "red"); Pthread exit(NULL); //print the string (show values of i, j) //print the string (show values of i,1) //copy the string "red" to buffer. int main(void) { pthread_t tid; //declaring vars int j = 1; buffer strcpy(malloc(100), "blue"); //Initialize buffer and copy the "blue" to it pthread_create(&tid,...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT