iTr*_*uth 10 c++ multithreading thread-local stdthread c++17
为了更好地理解这个问题,代码如下:
// 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 {
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)
根据basic.stc.thread,变量 t 被构造,应在线程退出时销毁。所以我认为即使函数thread_1返回,线程也不会退出。
这种行为符合标准吗?如果是这样,为什么?线程什么时候退出?
我还阅读了thread.threads,但似乎标准没有解释这一点。