Hon*_*gli 6 c++ linux thread-local
请考虑以下代码:
#include <stdio.h>
__thread bool foo = true;
int
main() {
printf("foo = %d\n", foo);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译并运行:
$ g++ tls.cpp -o tls -o tls
$ ./tls
Run Code Online (Sandbox Code Playgroud)
在某些系统上 - 例如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;
}
Run Code Online (Sandbox Code Playgroud)
为什么第一个代码示例在某些系统上崩溃,而后者却没有?是否__thread变量的静态初始化不起作用?可能会破坏操作系统?