Search code examples
c++multithreadingdetach

simple question about standard c++ multithreading


hi i am newbie learning c++ multithreading this ques may look stupid but just curious why it's happening would be amazing if somebody points out what is going on underhood

so,

class background_task
{
public:
    void operator()() const
    {

        for (int i = 0; i < 1000; ++i)
            std::cout << "Hello world " << i << std::endl;
    }
};

void Func()
{
    for(int i=0; i<1000;++i)
    std::cout << "Hello world " <<i<< std::endl;
};

void main()
{
    background_task bt;
    std::thread t(bt);

    //t.detach();
}

it gives me the runtime error saying "abort() has been called" and with detach() it works just fine. the either case, the new thread execute the loop all the way to end(1000times) i just guess the error happens because there's additional thread going when runtime thread exits. but even when i called detach(), there's still additional thread as well and output no error in this case.

i guess, in the destructor of std::thread, it checked like assert(!joinable()) or am i missing something else?


Solution

  • You need to either detach or join std::thread objects before they get destroyed. This is part of the API and documented in the destructor:

    std::thread::~thread
    Destroys the thread object.

    If *this has an associated thread (joinable() == true), std::terminate() is called.

    What you usually want is to join the thread, which blocks the current thread until the other thread has finished.

    If you want a thread that automatically joins on destruction, you can use C++20's std::jthread instead.