In: Computer Science
Modify the code below to implement the program that will sum up 1000 numbers using 5 threads.
1st thread will sum up numbers from 1-200
2nd thread will sum up numbers from 201 - 400
...
5th thread will sum up numbers from 801 - 1000
Make main thread wait for other threads to finish execution and sum up all the results.
Display the total to the user.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define N_OF_THREADS 4
void * print(void *tid){
printf("Hello %d\n", tid); pthread_exit(NULL);
}
int main(){
pthread_t threads[N_OF_THREADS];
int status, i; //
printf("Main. Creating thread %d\n", i);
for (int i=0; i<N_OF_THREADS; i++) {
printf("Main. Creating thread %d\n", i);
status = pthread_create(&threads[i], NULL, print, (void*)i);
if(status){
printf("Error %d\n", status);
exit(-1);
}
}
exit(NULL);
}
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define N_OF_THREADS 4
int start_num = 0;
int sum[4] ={0};
void * print(void *tid){
printf("Hello %d\n", tid); pthread_exit(NULL);
}
void *sum_of_num(void
* arg){
int thread_num = start_num++
for(int i=(thread_num*200)+1;i<=(thread_num+1)*200;i++){
sum[start_num]+=i;
}
}
int main(){
pthread_t threads[N_OF_THREADS];
int status, i; //
printf("Main. Creating thread %d\n", i);
for (int i=0; i<N_OF_THREADS; i++) {
printf("Main. Creating thread %d\n", i);
status = pthread_create(&threads[i], NULL, sum_of_num, (void*)i);
for
(
int
i = 0; i
<
N_OF_THREADS; i++)
pthread_join(threads[i],
NULL);
int
tsum = 0;
for
(
int
i = 0; i
<
N_OF_THREADS; i++)
t
sum += sum[i];
printf("Total is : %d",tsum);
if(status){
printf("Error %d\n", status);
exit(-1);
}
}
exit(NULL);
}