#include <pthread.h> #include <stdio.h> #include <string.h> int sum; void *runne
ID: 3726247 • Letter: #
Question
#include <pthread.h>
#include <stdio.h>
#include <string.h>
int sum;
void *runner(void *param);
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
if (argc != 2)
{
fprintf(stderr,"usage: a.out <integer value> ");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr,"%d must be >= 0 ",atoi(argv[1]));
return -1;
}
//default
pthread_attr_init(&attr);
//create
pthread_create(&tid,&attr,runner,argv[1]);
//join
pthread_join(tid,NULL);
printf("sum = %d ",sum);
}
void *runner(void *param)
{
int i, upper = atoi(param);
sum = 0;
for (i = 1; i <= upper; i++)
sum += i;
pthread_exit(0);
}
Explanation / Answer
Answer:
This program takes a positive integer as input, then passes that integer to a thread, which computes the sum of all integers from 1 to that integer, for example if input is 5 the threat will add 1 2 3 4 5 and print 15
Printing Is done in main function
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.