【发布时间】:2020-02-04 18:46:50
【问题描述】:
我在文件 tracker.hpp 中有一个变量:
namespace TRIALS
{
static thread_local int a = -1;
}
我在 ema.hpp/ema.cpp 文件中有另一个名为 EMP 的类
namespace Algo
{
class EMP
{
public:
void Sample();
};
}
namespace Algo
{
void EMP::Sample()
{
std::cout << "model " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
}
}
然后我有我的主文件
auto model = Algo::EMP();
void Simulate(const int a)
{
TRIALS::a = a;
model.Sample()
std::cout << "worker " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
}
int main()
{
std::cout << &TRIALS::a << std::endl;
const int nthreads = 1;
std::cout << "main " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
std::vector<std::thread> threads;
for(int i=0; i<nthreads; ++i)
{
threads.emplace_back(&Simulate, i);
}
for(auto &thread : threads)
{
thread.join();
}
std::cout << "main " << std::this_thread::get_id() << " " << &TRIALS::a << " " << TRIALS::a << std::endl;
return 0;
}
我只是运行一个线程进行调试,但这是输出:
0x7f9540b621d8
main 140279012532800 0x7f9540b621d8 -1(如预期)
model 140278985606912 0x7f953f1b469c -1(不应该是0吗??)
worker 140278985606912 0x7f953f1b4698 0(如预期)
main 140279012532800 0x7f9540b621d8 -1(如预期)
我的印象是每个线程都有自己的 TRIALS::a 本地副本。模型中的 a 正确地增加了,但是当它从同一个线程中的函数返回时,该值仍然为 0。我正在打印出线程 ID 和 a 的地址,我看到实际上有 3 个不同的TRIALS::a 的版本,尽管总共只有两个线程。
作为附加问题,static thread_local int a 和 thread_local int a 之间有什么区别?
【问题讨论】:
-
你知道
static变量是什么吗? -
你使用什么样的编译器/标准库/目标操作系统。本地线程实际上是特定于运行时的东西。
-
我正在使用 gcc 7.4 和 ubuntu 18.04
-
每个
.cpp文件都有自己的副本。您需要extern而不是static在文件之间共享全局。 -
@john 相反。
static这里的意思是“不是全球性的”。看到这个:stackoverflow.com/questions/14349877/…static很奇怪并且依赖于上下文。最糟糕的 C++ 结构之一。
标签: c++ multithreading thread-local