C: splitting a sum across threads without sharing
The simplest safe way to parallelize is to share nothing that changes. Each thread gets its own range of the input and its own output field in a struct. No thread writes to anything another thread reads, so no lock is needed. The main thread waits for all threads with pthread_join and then combines the partial results.
C
#include <pthread.h>
#include <stdio.h>
typedef struct {
int from;
int to;
long sum;
} Job;
static void *work(void *arg) {
Job *job = arg;
job->sum = 0;
for (int i = job->from; i <= job->to; i++) {
job->sum += i;
}
return NULL;
}
int main(void) {
Job jobs[4] = {{1, 250, 0}, {251, 500, 0}, {501, 750, 0}, {751, 1000, 0}};
pthread_t threads[4];
for (int t = 0; t < 4; t++) {
pthread_create(&threads[t], NULL, work, &jobs[t]);
}
long total = 0;
for (int t = 0; t < 4; t++) {
pthread_join(threads[t], NULL);
printf("part %d: %ld\n", t + 1, jobs[t].sum);
total += jobs[t].sum;
}
printf("total: %ld\n", total);
return 0;
}