DEV Community

Mukit, Ataul
Mukit, Ataul

Posted on

Pitfall with C++ Threads

In one of my programs, I declared a thread object accidentally inside an if condition. I completely forgot - the thread would be destroyed before properly finishing execution when the thread variable goes out of scope. It was heck of a trouble to find the core dump issue :
"terminate called without an active exception
Aborted (core dumped)"

My problematic code:

if(runnable){
    std::thread t([&app]() {
              app.run().
    });

}

Temporary Fix (I got more problems to take care off than to solve this one elegantly):

std::thread t([&app, &runnable]() {
    if(runnable){
        app.run();
    }       
            
});     

In any case, need to be very careful how and where your thread objects are declared and executed.

Signing off,

mukit

2020-07-21

Top comments (0)