我正在寻找同样的东西。正如我所见,在以各种方式搜索网络后,没有人回答您的问题,我得到了后续信息:假设在 linux (ubuntu) 上为 gcc 编译并使用 -m64,段寄存器 gs 的值为 0。隐藏部分段的(保存线性地址)指向线程特定的本地区域。该区域在该地址包含该地址的地址(64 位)。在较低地址存储所有线程局部变量。该地址是native_handle()
. 因此,为了访问线程本地数据,您应该通过该指针进行操作。
换句话说:(char*)&variable-(char*)myThread.native_handle()+(char*)theOtherThread.native_handle()
演示上述假设 g++,linux,pthreads 的代码是:
#include <iostream>
#include <thread>
#include <sstream>
thread_local int B=0x11111111,A=0x22222222;
bool shouldContinue=false;
void code(){
while(!shouldContinue);
std::stringstream ss;
ss<<" A:"<<A<<" B:"<<B<<std::endl;
std::cout<<ss.str();
}
//#define ot(th,variable)
//(*( (char*)&variable-(char*)(pthread_self())+(char*)(th.native_handle()) ))
int& ot(std::thread& th,int& v){
auto p=pthread_self();
intptr_t d=(intptr_t)&v-(intptr_t)p;
return *(int*)((char*)th.native_handle()+d);
}
int main(int argc, char **argv)
{
std::thread th1(code),th2(code),th3(code),th4(code);
ot(th1,A)=100;ot(th1,B)=110;
ot(th2,A)=200;ot(th2,B)=210;
ot(th3,A)=300;ot(th3,B)=310;
ot(th4,A)=400;ot(th4,B)=410;
shouldContinue=true;
th1.join();
th2.join();
th3.join();
th4.join();
return 0;
}