Solution: Parallel sum with POSIX threads

Solution: Parallel sum with POSIX threads

#include <stdio.h>
#include <pthread.h>

#define NUM_THREADS 3
#define CHUNK_SIZE 4

int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
int total_sum = 0;

pthread_mutex_t lock;

void* partial_sum(void* arg) {
    int id = *(int*)arg;
    int start = id * CHUNK_SIZE;
    int end = start + CHUNK_SIZE;

    int local_sum = 0;
    for (int i = start; i < end; i++) {
        local_sum += arr[i];
    }

    pthread_mutex_lock(&lock);
    total_sum += local_sum;
    pthread_mutex_unlock(&lock);

    return NULL;
}

int main() {
    pthread_t threads[NUM_THREADS];
    int thread_ids[NUM_THREADS];

    pthread_mutex_init(&lock, NULL);

    for (int i = 0; i < NUM_THREADS; i++) {
        thread_ids[i] = i;
        pthread_create(&threads[i], NULL, partial_sum, &thread_ids[i]);
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }

    pthread_mutex_destroy(&lock);

    printf("Final sum: %d\n", total_sum);
    return 0;
}
Solution: Parallel sum with POSIX threads