What is the _Thread_local keyword in C?
_Thread_local is a storage specifier introduced in the C11 version of C. It indicates thread storage duration.
Purpose
Variables declared with the _Thread_local keyword are local to the thread in which they are declared. This means that these variables are allocated when the thread begins and de-allocated when the thread ends.
Every thread has its own copy of the variable declared with the _Thread_local keyword.
Code
#include <stdio.h>#include "threads.h"#define SIZE 5int func(void *id){//_Thread_local variablestatic thread_local int var = 5;var += 5;//Print id of current thread and addr of varprintf("Thread ID:[%d], Value of var: %d\n", *(int*)id, var);return 0;}int main(void){thrd_t id[SIZE];//thread ID arrint arr[SIZE] = {1, 2, 3, 4, 5};//Creating 5 threadsfor(int i = 0; i < SIZE; i++) {thrd_create(&id[i], func, &arr[i]);}//Wait for threads to completefor(int i = 0; i < SIZE; i++) {thrd_join(id[i], NULL);}}
We declare a variable ( var ) using _Thread_local in the func() function.
The func() function prints the value of var and the id of the current thread.
The same value for var in each thread implies that the variables were local and distinct, despite the use of static. The value is never updated, as the variable is de-allocated once the thread goes out of scope.
We may also use the
_Thread_localkeyword withstaticorextern.
Free Resources