typestar

Passing work to a thread in C

One argument struct per thread, so nothing is shared by accident.

#include <pthread.h>

typedef struct {
    const int *values;
    size_t start;
    size_t end;
    long sum;
} Task;

static void *sum_range(void *arg) {
    Task *task = arg;
    task->sum = 0;
    for (size_t i = task->start; i < task->end; i++) {
        task->sum += task->values[i];
    }
    return NULL;
}

long parallel_sum(const int *values, size_t n, Task *tasks, size_t workers) {
    pthread_t threads[8];
    size_t chunk = (n + workers - 1) / workers;

    for (size_t w = 0; w < workers; w++) {
        size_t start = w * chunk;
        tasks[w].values = values;
        tasks[w].start = start;
        tasks[w].end = (start + chunk < n) ? start + chunk : n;
        pthread_create(&threads[w], NULL, sum_range, &tasks[w]);
    }

    long total = 0;
    for (size_t w = 0; w < workers; w++) {
        pthread_join(threads[w], NULL);
        total += tasks[w].sum;
    }
    return total;
}

How it works

  1. A pointer into an array of structs gives each thread its own.
  2. The struct carries both the input and the place for the result.
  3. The memory must outlive the thread, so no locals of a dead frame.

Keywords and builtins used here

The run, in numbers

Lines
37
Characters to type
774
Tokens
253
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 152 seconds.

Type this snippet

Step 2 of 3 in Starting threads, step 2 of 10 in Threads & concurrency.

← Previous Next →