Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread get abort exception in destructor in vc++

I am getting abort exception in simple VC++ program when main method completes.

Here is my sample test program.

#include "stdafx.h"
#include <thread>
#include <Windows.h>

class ThreadTest
{
public:
    ThreadTest()
    {
    }

    ~ThreadTest()
    {

    }

    void ThreadProc()
    {

    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    ThreadTest test;
    std::thread t = std::thread(&ThreadTest::ThreadProc, std::ref(test));

    Sleep(5000);

    return 0;
}

I have experience in nativate pthread_create functions but it seems that something is missing. When I put Sleep(15000); in ThreadProc method same issue happens without any changes.

like image 704
Rajdip Patel Avatar asked Mar 19 '26 15:03

Rajdip Patel


1 Answers

This is documented in std::thread's destructor: if a thread is destroyed while it is joinable, std::terminate is called.

Quote from the C++11 standard draft n3290 (§30.3.1.3 thread destructor):

If joinable() then terminate(), otherwise no effects. [ Note: Either implicitly detaching or joining a joinable() thread in its destructor could result in difficult to debug correctness (for detach) or performance (for join) bugs encountered only when an exception is raised. Thus the programmer must ensure that the destructor is never executed while the thread is still joinable. — end note ]

You must either join the thread, or detach it. Joining seems like the right option in your case.

like image 168
Mat Avatar answered Mar 21 '26 07:03

Mat