为了更好地理解这个问题,代码如下:
// code 1
#include <iostream>
#include <thread>
struct tls_test {
tls_test()
{ std::cout << "tls_test ctor\n"; }
~tls_test()
{ std::cout << "tls_test dtor\n"; }
void print() const
{ std::cout << "tls_test print\n"; }
};
thread_local tls_test t;
void thread_1()
{
std::cout << "thread_1 started\n";
t.print();
std::cout << "thread_1 return\n";
}
int main()
{
std::thread trd{ thread_1 };
trd.join();
std::cout << "main return\n";
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 TDM-GCC 和 Windows 10 来测试该程序。这是输出:
// code 1
#include <iostream>
#include <thread>
struct tls_test { …Run Code Online (Sandbox Code Playgroud)