PES1UG24CS838_VIKASKS
PES1UG24CS838_VIKASKS
Programming Exercise-2
NAME VIKAS K S
SRN PES1UG24CS838
SECTION J
3) Using mutex locks, write a program that creates multiple threads
and performs a parallel sum of an array of integers. Each thread
should work on a portion of the array and update a global variable
that stores the sum. The program should use mutex locks to protect
the access to the global variable and avoid race conditions.
Code :
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_exit(NULL);
}
int main() {
// Initialize the array with values (e.g., 1 to
ARRAY_SIZE)
for (int i = 0; i < ARRAY_SIZE; i++) {
arr[i] = i + 1;
}
pthread_t threads[NUM_THREADS];
ThreadData thread_data[NUM_THREADS];
int segment_size = ARRAY_SIZE / NUM_THREADS;
return 0;
}
Output :