我遇到了一些关于thread_local的奇怪行为,不确定是我做错了什么还是GCC的bug。 我有以下最小复现场景:
#include <iostream>
using namespace std;
struct bar {
struct foo {
foo () {
cerr << "foo" << endl;
}
int i = 42;
};
static thread_local foo FOO;
};
static thread_local bar::foo FREE_FOO;
thread_local bar::foo bar::FOO;
int main() {
bar b;
cerr << "main" << endl;
// cerr << FREE_FOO.i << endl;
cerr << b.FOO.i << endl;
return 0;
}
在上面的注释行之前,输出结果如下:
main
0
取消注释后,它变成了这样:
main
foo
foo
42
42
这里是不是有什么愚蠢的地方我没有注意到?
$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/4.8/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.8.1-10ubuntu9' --with-bugurl=file:///usr/share/doc/gcc-4.8/README.Bugs --enable-languages=c,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.8 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.8 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-4.8-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-4.8-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.8.1 (Ubuntu/Linaro 4.8.1-10ubuntu9)
更新:
这也会产生意外的结果:
#include <iostream>
using namespace std;
template<class T>
struct bar {
struct foo {
foo () {
cerr << "bar::foo" << endl;
}
int i = 42;
};
void baz() {
cerr << bar::FOO.i << endl;
}
static thread_local foo FOO;
};
struct far {
struct foo {
foo () {
cerr << "far::foo" << endl;
}
int i = 42;
};
void baz() {
cerr << far::FOO.i << endl;
}
static thread_local foo FOO;
};
template<class T> thread_local typename bar<T>::foo bar<T>::FOO;
thread_local typename far::foo far::FOO;
int main() {
cerr << "main" << endl;
bar<int> b;
b.baz();
far f;
f.baz();
return 0;
}
结果:
main
0
far::foo
bar::foo
42
static thread_local bar :: foo FREE_FOO;
中的static
没有任何效果,因为您只是修改了链接(默认为内部)。删除它,您将获得相同的行为。 - Andythread_local
变量”的代码路径。 - Richard Smith