Question: This program uses a thread to generate a summation of 1 to n, that is, 1+2+3.. +n. Let us modify this code (consum.c) as follows.
This program uses a thread to generate a summation of 1 to n, that is, 1+2+3.. +n. Let us modify this code (consum.c) as follows.
Instead of one thread summing all numbers from 1 to n, let us split the task into two halves and assign each half to two separate threads (that means you need to create two threads). One thread sums from 1 to n/2 (assume n is even), and the other thread sums from n/2 + 1 to n. Once the two children threads join, the parent/main program sums the two results to obtain the overall summation and prints the summation.
Compile your program using gcc -lpthread and run on the Linux VM
#include
int sum; /* this data is shared by the thread(s) */
void *runner(void *param); /* the thread */
int main(int argc, char *argv[]) { pthread_t tid; /* the thread identifier */ pthread_attr_t attr; /* set of attributes for the thread */
if (argc != 2) { fprintf(stderr,"usage: a.out
if (atoi(argv[1]) < 0) { fprintf(stderr,"Argument %d must be non-negative ",atoi(argv[1])); /*exit(1);*/ return -1; }
/* get the default attributes */ pthread_attr_init(&attr);
/* create the thread */ pthread_create(&tid,&attr,runner,argv[1]);
/* now wait for the thread to exit */ pthread_join(tid,NULL);
printf("sum = %d ",sum); }
/** * The thread will begin control in this function */ void *runner(void *param) { int i, upper = atoi(param); sum = 0;
if (upper > 0) { for (i = 1; i <= upper; i++) sum += i; }
pthread_exit(0); }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
