For a better understanding of this question, here is the code:
// 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";
}
I'm using TDM-GCC and windows 10 to test this program. here is the output:
thread_1 started
tls_test ctor
tls_test print
thread_1 return
main return
According to basic.stc.thread, the variable t is constructed, shall be destroyed on thread exit. so I think that thread is not exit even the function thread_1
returns.
Does this behavior meet the standards? If so, why? When does the thread exit?
I also read thread.threads, but seems like the standard does not explain this.
{ std::thread trd{ thread_1 }; trd.join(); } std::cout << "main return\n";
change something? Could it be issue with order of deinitialization of global (std::cout
,t
)? – Lycopodiumstd::thread
, I noticed that it's implemented using pthread, so I trying to call pthread_cancel and pthread_exit, but dtor for that thread_local still not called – Thanasipthread_cancel
andpthread_exit
does nothing to the c++ wrapper, and the thread is dead after.join()
so that's not the problem. It's the cleanup of the thread local storage that's borked. – Kunkelthread_local
objects should be called. However, the timing and order of these destructors being called can depend on the runtime library and thread implementation used by the compiler. In your case, with TDM-GCC on Windows 10, it's possible that the runtime library does not call destructors forthread_local
objects in a straightforward manner due to the specifics of thread termination on the platform. – Hokusai