_Thread_local storage class specifier in C?
Asked Answered
L

1

8

I read a note in the book C How to Program 7th about some new standard C storage class named _Thread_local:

The new C standard adds storage class specifier _Thread_local, which is beyond this book's scope.

I looked for it in Google and here but nothing show up. Could someone please provide me some link about it?

Lindon answered 12/1, 2013 at 2:39 Comment(3)
_Thread_local was added in C11 and the new standard header which contains this is <threads.h>. You can look at standard for information. GCC doesn't have it yet. You'll have to find a compiler that implements this C11 feature.Lorentz
@KingsIndian, many compilers, including gcc, already implement the feature, but not yet the keyword. gcc has it as __thread and other compilers might have it as __declspec(thread). Usually a simple #define of _Thread_local does the trick.Swinish
GCC 6 and 7 support C11, except that they don't support <threads.h> . GCC 9 definitely supports it, but I don't know about GCC 8.Miscarry
A
10

Variables marked with _Thread_local are given "thread" storage duration -- that is, they are allocated when a thread begins, and deallocated when the thread ends. Such variables are "local" to the thread, since every thread has its own copy of the variable. This is in contrast to static storage duration (one instance of the variable for the entire program). See http://en.cppreference.com/w/c/language/storage_class_specifiers for more details.

Actual answered 12/1, 2013 at 2:51 Comment(3)
Is the "static" keyword redundant when _Thread_local is used?Navarra
sorry, it may be very old to re-open but why do we need such a variable, why cannot we simply declare variable inside the function instead of declaring it in global space and say it be local to threadPropylaeum
@EdwardFalk static on a global variable makes the variable visible only in that compilation unit; static on a local variable makes it statically allocated but visible only to the containing scope. @ sravs what if you want a global variable that has a different value in every thread? That’s what this modifier is for.Actual

© 2022 - 2024 — McMap. All rights reserved.