静态变量自动是线程本地的吗?
本地静态变量是自动线程本地的,还是在线程之间共享?
void f() {
static int x; // <-- need explicit _Thread_local ?
}
Are local static
variables automatically thread local, or are they shared between threads?
void f() {
static int x; // <-- need explicit _Thread_local ?
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 C 语言规范承认线程或对它们有任何支持之前,就存在块范围变量的
static
,更不用说专门的_Thread_local
了。在这种情况下,当不与_Thread_local
结合使用时,它指定静态存储持续时间,这意味着该变量在程序执行开始时就存在(就好像)并且存在并且在程序的整个运行过程中保持其最后存储的值。具有静态存储持续时间的对象由所有线程共享。另一方面,
_Thread_local
始终指定线程存储持续时间,这意味着如此声明的对象存在并在线程的整个生命周期内维护其最后存储的值,并且声明的标识符在每个线程中指定不同的对象。当对象在块作用域中声明为_Thread_local
时,它还必须带有extern
或static
限定符,以传达其链接< /em> -- 外部或无。块作用域中任何类型的
extern
声明都是不常见的,但它们偶尔确实有用途。不过,大多数时候,static _Thread_local
正是您想要的线程局部、块作用域变量。There was
static
for block-scope variables before the C language specification acknowledged threads or had any support for them, much less_Thread_local
specifically. In that context, when not combined with_Thread_local
, it specifies static storage duration, meaning that the variable comes into existence (as if) at the beginning of program execution and exists and maintains its last-stored value for the entire run of the program. An object with static storage duration is shared by all threads.On the other hand,
_Thread_local
always specifies thread storage duration, which means that the object so declared exists and maintains its last-stored value for the entire lifetime of a thread, and that the declared identifier designates a different object in each thread. When an object is declared_Thread_local
at block scope, it must also bear either theextern
orstatic
qualifier, which conveys its linkage -- external or none.extern
declarations of any kind at block scope are unusual, but they do occasionally serve a useful purpose. Most of the time, though,static _Thread_local
is what you will want for thread-local, block-scope variables.static
和_Thread_local
指定两个不同的东西。声明为
static
的变量具有静态存储持续时间并且具有完整的程序生命周期。声明_Thread_local
的变量具有线程存储持续时间,并且每个线程都存在一个它的实例。static
and_Thread_local
specify two different things.A variable declared as
static
has static storage duration and has full program lifetime. A variable declared_Thread_local
has thread storage duration and an instance of it exists for each thread.它们是线程之间共享的值。正如您自己已经提到的,如果您想让每个线程具有独立的值,则将其声明为
_Thread_local static int x;
They are shared value between threads. As you already mentioned by yourself, if you want to make have independently value for each of thread then declare it something line that
_Thread_local static int x;