静态变量自动是线程本地的吗?

发布于 2025-01-11 12:27:52 字数 128 浏览 0 评论 0原文

本地静态变量是自动线程本地的,还是在线程之间共享?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寄意 2025-01-18 12:27:52

在 C 语言规范承认线程或对它们有任何支持之前,就存在块范围变量的 static ,更不用说专门的 _Thread_local 了。在这种情况下,当不与_Thread_local结合使用时,它指定静态存储持续时间,这意味着该变量在程序执行开始时就存在(就好像)并且存在并且在程序的整个运行过程中保持其最后存储的值。具有静态存储持续时间的对象由所有线程共享。

另一方面,_Thread_local 始终指定线程存储持续时间,这意味着如此声明的对象存在并在线程的整个生命周期内维护其最后存储的值,并且声明的标识符在每个线程中指定不同的对象。当对象在块作用域中声明为 _Thread_local 时,它还必须带有 externstatic 限定符,以传达其链接< /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 the extern or static 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.

风向决定发型 2025-01-18 12:27:52

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.

遇到 2025-01-18 12:27:52

它们是线程之间共享的值。正如您自己已经提到的,如果您想让每个线程具有独立的值,则将其声明为 _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;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文