【发布时间】:2014-01-23 23:40:00
【问题描述】:
我有一个共享库 (libtest.cpp) 和一个简单的程序 (test.cpp)。我希望他们共享一个线程局部变量 gVar。共享库通过 LD_PRELOAD 链接。
这是我的共享库 libtest.cpp 的代码:
#include<stdio.h>
__thread int gVar;
void print_gVar(){
printf("%d\n", gVar);
}
下面是 test.cpp 的代码。
#include<stdio.h>
__thread int gVar;
void __attribute__((weak)) print_gVar();
int main(){
gVar = 10;
print_gVar();
return 0;
}
我使用下面的脚本来编译和运行它们。
g++ -g -shared -fPIC -olibtest.so libtest.cpp
g++ -g -fPIC -o test test.cpp
LD_PRELOAD=./libtest.so ./test
预期结果为 10,因为 test.cpp 中的赋值会影响 libtest.cpp 中的 gVar。但是,我只得到了0。似乎libtest.cpp中的gVar和test.cpp中的gVar没有链接。
我做了一些额外的测试:
如果我在任何文件中将__attribute__((weak)) 添加到gVar 的声明中,输出仍然是0。
如果我从两个文件中删除 __thread,则结果为 10(成功)。
如果我在libtest.cpp中gVar的声明中添加extern和__attribute__((weak)),就会出现分段错误。
我猜LD_PRELOAD 和__thread 一定有问题。但我想不通。
谁能告诉我如何让它工作?非常感谢!
【问题讨论】:
标签: c++ linux multithreading pthreads