Part 3 of 6 · 3 min read
Arguments and results
In plain words: A start function receives exactly one void *. To pass several values, put them in a struct and pass its address. The thread can also write its answer into the same structure. Because threads share memory, nothing needs to be copied.
The next program adds up a million numbers using 4 threads. Each thread gets a range of the array and a field to put its sum in:
#include <stdio.h>
#include <pthread.h>
#define NT 4
#define N 1000000
static long data[N];
struct job { int from, to; long sum; };
static void *partial_sum(void *arg) {
struct job *j = arg;
long s = 0;
for (int i = j->from; i < j->to; i++) s += data[i];
j->sum = s;
return NULL;
}
int main(void) {
for (int i = 0; i < N; i++) data[i] = i % 10;
pthread_t t[NT];
struct job jobs[NT];
for (int k = 0; k < NT; k++) {
jobs[k].from = k * (N / NT);
jobs[k].to = (k + 1) * (N / NT);
pthread_create(&t[k], NULL, partial_sum, &jobs[k]);
}
long total = 0;
for (int k = 0; k < NT; k++) {
pthread_join(t[k], NULL);
printf("thread %d: %ld\n", k, jobs[k].sum);
total += jobs[k].sum;
}
printf("total %ld\n", total);
return 0;
}
thread 0: 1125000
thread 1: 1125000
thread 2: 1125000
thread 3: 1125000
total 4500000
Check by hand: the values cycle 0 to 9, and each cycle sums to 45. A quarter of the array is 250,000 numbers, which is 25,000 cycles, so each thread's sum is 25,000 × 45 = 1,125,000. Four threads give 4,500,000. The result agrees with a separate calculation of the full sum.
Two design points make this safe without any locking. Each thread writes only to its own jobs[k], and each reads a different part of data. No two threads write the same variable, so there is no race (Level 4). The main thread reads the sums only after pthread_join returns, when the thread has ended.
A thread can also return a value through return or pthread_exit(value), and pthread_join(t, &res) delivers it. The returned value must not point to a local variable of the thread, because that stack goes away. It can point to heap memory:
static void *square(void *arg) {
long n = (long)arg;
long *r = malloc(sizeof *r);
*r = n * n;
return r; /* the joiner must free it */
}
Joining a thread started with n = 12 printed thread returned 144, and 12 × 12 is 144.
Common mistake
Passing the address of a loop variable. In the loop for (int i = 0; i < 3; i++) pthread_create(&t[i], NULL, show, &i); all three threads receive a pointer to the same i, and i keeps changing. In a test, the threads were expected to print 0, 1 and 2 and printed 2 three times on the test machine. The values depend on timing and can change from run to run. Give each thread its own copy: an element of an array, a struct per thread as above, or a malloced value.
Check yourself:
1. How can a thread receive three values through one void *?
2. Why is it safe that each thread writes to jobs[k].sum?
3. Why must a thread not return the address of one of its own local variables?