samedi 5 janvier 2019

Why getting main thread id instead of child thread id when terminate called

I have written a sample program wherein I have intentionally not joined thread t1.

Example:

$include <iostream>
#include <thread>
using namespace std;
void fun3()
{
    cout << "t1:: "<<this_thread::get_id() << endl;//prints t1 Thread ID.
}
void myterminate() {
    cout << "terminate:: "<<this_thread::get_id() << endl;//prints main thread ID!!  
                                                      //Why it is not printing thread t1's id ??


    abort();  // forces abnormal termination
}
int main()
{
    cout << "main:: "<<this_thread::get_id() << endl;//prints main Thread ID
    std::set_terminate(myterminate);
    thread t1(fun3);
    //t1.join(); // intentionally commented to see who will call terminate method.
    getchar();
    return 0;
}

My understanding is (which may be wrong):

When the control reached end of main() function, the destructor of thread t1 will be called.

~thread() _NOEXCEPT
{
    if (joinable())
        _XSTD terminate(); //<-- thread t1 will be calling this method
}

Since, thread t1 is invoking terminate() method, then, myterminate() method should print t1's thread id. But, instead of printing t1's thread id it is printing main thread id.

So my doubt is - why myterminate() method prints main's thread id instead of child thread's id ?

PS- I am learning thread programming, so please forgive if I have missed an obvious concept.

Thanks.

Aucun commentaire:

Enregistrer un commentaire