typestar

Creating threads in C

pthread_create starts a thread running one function; pthread_join waits for it.

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

static void *worker(void *arg) {
    long id = *(long *) arg;
    printf("worker %ld\n", id);
    return arg;
}

int main(void) {
    pthread_t threads[3];
    long ids[3] = {0, 1, 2};

    for (int i = 0; i < 3; i++) {
        if (pthread_create(&threads[i], NULL, worker, &ids[i]) != 0) {
            return 1;
        }
    }
    for (int i = 0; i < 3; i++) {
        void *result = NULL;
        pthread_join(threads[i], &result);
        printf("joined %ld\n", *(long *) result);
    }
    return 0;
}

How it works

  1. The thread function takes and returns void *.
  2. Each thread needs its own argument, never a shared loop variable.
  3. Joining is what makes the result and the cleanup safe.

Keywords and builtins used here

The run, in numbers

Lines
25
Characters to type
455
Tokens
165
Three-star pace
100 tpm

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

Type this snippet

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

Next →