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
- Each thread reads and writes an independent instance.
- No lock is needed, because nothing is shared.
- It suits per-thread scratch buffers and counters.
Keywords and builtins used here
_Thread_localbump_localcharconstintlast_messagereturnsizeofstaticvoid
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.
Step 2 of 2 in Lock-free & local, step 9 of 10 in Threads & concurrency.