CKTIS / C
thread_local — a separate object for each thread
thread_local gives an object thread storage duration. _Thread_local remains an equivalent but obsolescent spelling.
Version: C23; repository compiler flag, production runtime not attested
Syntax
thread_local int counter = 0;
static thread_local int private_counter = 0;
extern thread_local int external_counter;
/* At block scope: */
/* static thread_local int local_counter = 0; */
/* Obsolescent equivalent spelling: _Thread_local */thread_local is a C23 keyword requiring no header. Each thread has a separate object lasting throughout that thread's execution. _Thread_local is an equivalent, obsolescent spelling.
At block scope, static or extern is also required; every declaration of the same object must retain thread_local. The specifier cannot declare functions. Initialization occurs at thread startup, not on each function call.
Indirect access from another thread has implementation-defined behavior. The example demonstrates persistence between calls, not thread isolation.
Examples
#include <stdio.h>
static int next(void)
{
static thread_local int counter = 0;
return ++counter;
}
int main(void)
{
int first = next();
int second = next();
printf("%d %d\n", first, second);
return 0;
}
Result
1 2
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.