What is the _Thread_local keyword in C?

Share

_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.

_Thread_local variable de-allocation

Code

#include <stdio.h>
#include "threads.h"
#define SIZE 5
int func(void *id)
{
//_Thread_local variable
static thread_local int var = 5;
var += 5;
//Print id of current thread and addr of var
printf("Thread ID:[%d], Value of var: %d\n", *(int*)id, var);
return 0;
}
int main(void)
{
thrd_t id[SIZE];
//thread ID arr
int arr[SIZE] = {1, 2, 3, 4, 5};
//Creating 5 threads
for(int i = 0; i < SIZE; i++) {
thrd_create(&id[i], func, &arr[i]);
}
//Wait for threads to complete
for(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_local keyword with static or extern.

Copyright ©2024 Educative, Inc. All rights reserved