c / expert
Snippet
Thread-Local Storage with _Thread_local
Introduced in C11, the _Thread_local storage class specifier defines variables that have thread storage duration. Each thread receives its own separate instance of the variable, initialized once per thread. This allows for thread-safe global-like state without the performance overhead of mutexes or semaphores for synchronization.
snippet.c
1
2
3
4
5
6
7
8
9
#include <threads.h>#include <stdio.h>_Thread_local int thread_count = 0;void increment() {thread_count++;printf("Thread count: %d\n", thread_count);}
Breakdown
1
_Thread_local int thread_count = 0;
Declares a variable that is unique to each execution thread.
2
thread_count++;
Increments the instance of the variable belonging only to the current thread.