In: Computer Science
using C thank you
Must submit as MS Word file with a screenshot of the 3 outputs. Run your program 3 times.
the output must be in a screenshot not typed for the each time you run the program. thank you
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 <stdio.h> 
#include<stdlib.h>
#include<pthread.h> 
#define MAX 1000     // size of array 
#define MAX_THREAD 5    // maximum number of threads 
int a[1000] = {[0 ... 999] = 2};    // initialized array elements to 2: for say as an example
int sum_of_partial[5] = { 0 };     //  to contain partial sums of array parts
int part = 0;     //  to identify parts of the array to compute
  
void* sum_of_array(void* arg) 
{ 
  
    // Each thread computes sum of 1/5th of array as mentioned in the question
    int thread_part = part++; 
  
    for (int i = thread_part * (MAX / 5); i < (thread_part + 1) * (MAX / 5); i++) 
        sum_of_partial[thread_part] += a[i]; 
} 
  
// Main program
int main() 
{ 
  
    pthread_t threads[MAX_THREAD]; 
  
    // Creating all the 5 threads 
    for (int i = 0; i < MAX_THREAD; i++) 
    {
        pthread_create(&threads[i], NULL, sum_of_array, (void*)NULL); 
    }
    // joining all the 5 threads (wait for all 5 threads) 
    for (int i = 0; i < MAX_THREAD; i++) 
    {
        pthread_join(threads[i], NULL); 
    }
    // adding the sum of all 5 parts from 5 threads
    int total_sum = 0; 
    for (int i = 0; i < MAX_THREAD; i++) 
        total_sum += sum_of_partial[i]; 
  
    printf("The final sum is: %d", total_sum); 
  
    return 0; 
}