Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this simple threaded C++ program crash upon exit unless I call thread.join()?

The program below will end up failing with a message regarding abort() being called.

I'm starting a thread that simple prints to cout. If I use std::this_thread::sleep_for(), I get the error. If I remove this, I get the error. If I call join() on the thread, everything works fine.

Shouldn't the thread have terminated long before the 1000 ms delay was up? Why is this causing an error? I can't believe calling join() is a requirement for a thread.

#include <thread>
#include <iostream>

class ThreadTest
{
public:
    ThreadTest() : _t{ &ThreadTest::Run, this } {}
    void Wait() { _t.join(); }

private:

    void Run(){
        std::cout << "In thread" << std::endl;
    }

    std::thread _t;
};

int main(int argc, char *argv[])
{
    ThreadTest tt;

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    // tt.Wait();

    return 0;
}
like image 635
Steve Avatar asked Jul 30 '26 13:07

Steve


1 Answers

According to cppreference on thread class destructor :

~thread(): Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.

And joinable() :

[...] A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

So you have to call join() explicitely before your thread variable is automatically destroyed or use the detach() member function.

like image 94
Chnossos Avatar answered Aug 02 '26 04:08

Chnossos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!