jeudi 13 juillet 2017

C++ Unhandle exception on Thread join()

I have a class Foo:

class Foo
{
   void bar();
   std::vector<std::thread>     mThreadPool;
}

which contains a vector of threads.

Inside my bar() method I have something like:

void Foo::bar()
{
    mThreadPool.push_back(std::thread(handler));

    killThemAll();
}

Where my handler is:

void handler()
{
   loop(); //contains a loop until a button is pressed
}

And the killThemAll() method is:

void killThemAll()
{
    for (auto& iThread : mThreadPool)
    {
        iThread.join();
    }
}

So far so good... everything works as expected.

But now, if I change my Bar() method to :

void Foo::bar()
{
    while(true) // I WANT THIS LOOP HERE!
    {
        mThreadPool.push_back(std::thread(handler));

        killThemAll();
    }
}

Then I have an unhandle exception on join()

void killThemAll()
{
    for (auto& iThread : mThreadPool)
    {
        iThread.join(); // UNHANDLE EXCEPTION HERE!
    }
}

What am I doing wrong here, since I close the thread correctly?

I see that on the thread file, on the join() method:

inline void thread::join()
    {   // join thread
    if (!joinable())
        _Throw_Cpp_error(_INVALID_ARGUMENT);
    if (_Thr_is_null(_Thr)) // <---- it crashes here!!!!!!!!!!!!!!!!!!!!!
        _Throw_Cpp_error(_INVALID_ARGUMENT);
    if (get_id() == _STD this_thread::get_id())
        _Throw_Cpp_error(_RESOURCE_DEADLOCK_WOULD_OCCUR);
    if (_Thrd_join(_Thr, 0) != _Thrd_success)
        _Throw_Cpp_error(_NO_SUCH_PROCESS);
    _Thr_set_null(_Thr);
    }

The Error:

Unhandled exception at 0x000007FEFD52A06D in TestThread.exe: Microsoft C++ exception: std::system_error at memory location 0x000000000013F760.

Aucun commentaire:

Enregistrer un commentaire