【问题标题】:Segmentation fault when accessing statically initialized __thread variable访问静态初始化的 __thread 变量时出现分段错误
【发布时间】:2013-12-23 00:56:57
【问题描述】:

考虑以下代码:

#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 变量的静态初始化不应该工作吗?操作系统会不会坏?

【问题讨论】:

  • 看:bugzilla.redhat.com/show_bug.cgi?id=731228 好像是gcc 4.6的问题。
  • 有六个类似的报告在谈论段错误。如果选择更大的类型(可能是int)可行,我会尝试,否则尝试使用更新的 GCC。
  • 效果很好。谢谢达蒙!

标签: c++ linux thread-local


【解决方案1】:

您忘记告诉编译器您需要线程支持。最有可能的标志是-pthread

【讨论】:

  • 确定吗?您需要特殊的编译器标志来使用标准 C++11 关键字吗?如果是这样的话,我会感到惊讶(尽管老实说我从来没有使用过或关心过__thread,所以我不知道)。
  • @Damon 这不是标准的 C++11 关键字。我想你在考虑thread_local。 __thread,据我所知,是一个 GNU 扩展。我会试试 -pthread,我什至不知道这在 Linux 上是必需的。
  • 没有骰子。使用 -pthread 编译并没有什么不同。也没有链接到 -lpthread。
猜你喜欢
  • 2012-09-01
  • 1970-01-01
  • 2011-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 2011-08-22
相关资源
最近更新 更多