Exercise: Parallel sum with POSIX threads

Write code to solve the problem.

Write a C program that computes the sum of all elements in an integer array using multiple POSIX threads.

The array should be divided into equal parts, and each thread should compute the sum of its assigned portion. The main thread should then combine these partial sums to produce the final result. Your program must ensure that the result is correct even when multiple threads update shared data.

Requirements:

  • Use an array of 12 integers.

  • Use 3 threads.

  • Each thread should sum 4 elements.

  • Use a global variable to store the total sum. Protect the update to the global sum using a mutex.

Expected output:

Final sum: 78

Exercise: Parallel sum with POSIX threads

Write code to solve the problem.

Write a C program that computes the sum of all elements in an integer array using multiple POSIX threads.

The array should be divided into equal parts, and each thread should compute the sum of its assigned portion. The main thread should then combine these partial sums to produce the final result. Your program must ensure that the result is correct even when multiple threads update shared data.

Requirements:

  • Use an array of 12 integers.

  • Use 3 threads.

  • Each thread should sum 4 elements.

  • Use a global variable to store the total sum. Protect the update to the global sum using a mutex.

Expected output:

Final sum: 78

#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) {
    /* Write your code here */
    return NULL;
}

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

    pthread_mutex_init(&lock, NULL);

    /* Create threads */

    /* Wait for threads */

    pthread_mutex_destroy(&lock);

    printf("Final sum: %d\n", total_sum);
    return 0;
}
Try it yourself