jeudi 18 juin 2020

Why can detached thread in C++11 execute even if the destructor has been called

I just read the doc about std::thread.detach() in C++11.

Here is my test:

#include <iostream>
#include <thread>
#include <chrono>

static int counter = 0;    

void func()
{
    while (true) {
        std::cout<<"running..."<<std::endl;
        std::cout<<counter++<<std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}


int main()
{
    {
        std::thread t(func);
        t.detach();
    } // t is released after this line
    // t has died, so who is holding the resources of the detached thread???

    std::cin.get();

    return 0;
}

This code works as expected. So it seems that the thread can keep running even if its destructor has been invoked. Is this true?

If it's true, who on earth holds the resources of the thread after the object t is released? Is there some mechanism to hold the resources, for example, a hidden anonymous object?

Aucun commentaire:

Enregistrer un commentaire