Question: #include #include #include #define SIZE 5 0 0 0 #define THREADS 8 int numbers [ SIZE ] ; int partial _ sums [ THREADS ]

#include #include #include #define SIZE 5000 #define THREADS 8 int numbers[SIZE]; int partial_sums[THREADS]={0}; // To store sum from each thread // Function to read integers from file and store in global array void readfile(const char *filename){ FILE *file = fopen(filename,"r"); if (file == NULL){ perror("Unable to open file"); exit(1); } for (int i =0; i SIZE; i++){ fscanf(file,"%d", &numbers[i]); } fclose(file); }// Thread function to compute the sum of a segment void *compute_sum(void *arg){ int thread_id =*(int *)arg; int start = thread_id *(SIZE / THREADS); int end = start +(SIZE / THREADS); for (int i = start; i end; i++){ partial_sums[thread_id]+= numbers[i]; } printf("Thread %d Sum: %d
", thread_id +1, partial_sums[thread_id]); pthread_exit(0); } int main(int argc, char *argv[]){ if (argc !=2){ fprintf(stderr, "Usage: %s
", argv[0]); return 1; } readfile(argv[1]); printf("Reading file: %s
", argv[1]); pthread_t threads[THREADS]; int thread_ids[THREADS]; int total_sum =0; // Create threads for (int i =0; i THREADS; i++){ thread_ids[i]= i; pthread_create(&threads[i], NULL, compute_sum, &thread_ids[i]); }// Wait for threads to complete for (int i =0; i THREADS; i++){ pthread_join(threads[i], NULL); total_sum += partial_sums[i]; // Sum up each thread's partial result } printf("Total Sum is: %d
", total_sum); return 0; }
Reading file: input.txt
Thread 3 Sum: 0
Thread 1 Sum: 13568
Thread 2 Sum: 7634
Thread 4 Sum: 0
Thread 5 Sum: 0
Thread 6 Sum: 0
Thread 7 Sum: 0
Thread 8 Sum: 0
Total Sum is: 21202
Why i got output like this ?
#include #include #include #define SIZE 5 0 0 0

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!