c++ - 访问静态初始化的 __thread 变量时出现段错误

标签 c++ linux thread-local

考虑以下代码:

#include <stdio.h>

__thread bool foo = true;

int
main() {
    printf("foo = %d\n", foo);
    return 0;
}

编译并运行:

$ g++ tls.cpp -o tls -o tls
$ ./tls

在某些系统上——例如 Amazon Linux 2013.09.0、ami-5b792c32、内核 3.4.62-53.42.amzn1.i686、g++ 4.6.3 20120306 (Red Hat 4.6.3-2)——这会导致一旦访问 foo 就会出现段错误。

另一方面,在代码中显式初始化 foo 不会导致段错误:

#include <stdio.h>

__thread bool foo = true;

int
main() {
    foo = true;  /* Added!! */
    printf("foo = %d\n", foo);
    return 0;
}

为什么第一个代码示例在某些系统上会崩溃,而后者不会? __thread 变量的静态初始化不应该起作用吗?操作系统会坏吗?

最佳答案

你忘了告诉编译器你想要线程支持。最有可能的是,标志是 -pthread

关于c++ - 访问静态初始化的 __thread 变量时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20410943/

相关文章:

C++ 为什么 'note: see reference to class template instantiation being compiled'

linux - 将 shell 变量中的空格替换为 -

java - 从 linux 命令创建 Java 字符串

java - 我的 ThreadLocal 始终包含并返回 null

c++ - thread_local 静态类在程序退出时在无效地址处被销毁

c++ - gets() 不接受输入

c++ - 文件 stat() 与 access() 检查目录权限

c++ - 如何部署依赖动态库的应用程序?

c++ - epoll集合中fd与关联状态的映射