Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is the _Thread_local keyword in C?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

c

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring