John Smith John Smith - 2 days ago 5
C++ Question

std::thread::join blocks indefinitely out of main

std::thread::join
does not return, even if the thread routine is exited.

Guess, I have a class.

class A
{
public:
A()
{
this->thr = std::thread(&A::foo, this);
}
~A()
{
this->join();
}
void join()
{
this->cond.notify_all();
if (this->thr.joinable())
{
this->thr.join();
}
}

private:
void foo()
{
std::mutex mtx;
std::unique_lock<std::mutex> lck(mtx);
this->cond.wait(lck);
MessageBox(L"I'm done!");
}

private:
std::thread thr;
std::condition_variable cond;
};


My application contains the only instance of
A
. It is a global variable.
If
A::join
is called from the destructor,
std::thread::join
blocks forever.
If I call
A::join
manually (e.g. before exiting
main
), everything is alright.

My
main
looks like this:

A a;
int main()
{
auto timeout = std::chrono::seconds(3);
std::this_thread::sleep_for(timeout);

// a.join();
}


By the way, MessageBox is always executed.

Is that the same problem as here?

Answer

Yes it is the same bug as in the referenced link since your example also hangs on _Thrd_join. You could be interrested in this question which contains a far more detailed analysis.

Comments