typestar

Thread-local storage in C

_Thread_local gives every thread its own copy of a variable.

#include <stdio.h>

static _Thread_local int calls = 0;
static _Thread_local char scratch[64];

int bump_local(void) {
    calls++;
    snprintf(scratch, sizeof scratch, "call %d", calls);
    return calls;
}

const char *last_message(void) {
    return scratch;
}

How it works

  1. Each thread reads and writes an independent instance.
  2. No lock is needed, because nothing is shared.
  3. It suits per-thread scratch buffers and counters.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
248
Tokens
58
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 2 in Lock-free & local, step 9 of 10 in Threads & concurrency.

← Previous Next →