How to cleanly exit a threaded C++ program?

Rishav Jain picture Rishav Jain · Apr 18, 2018 · Viewed 12.8k times · Source

I am creating multiple threads in my program. On pressing Ctrl-C, a signal handler is called. Inside a signal handler, I have put exit(0) at last. The thing is that sometimes the program terminates safely but the other times, I get runtime error stating

abort() has been called

So what would be the possible solution to avoid the error?

Answer

Some programmer dude picture Some programmer dude · Apr 18, 2018

The usual way is to set an atomic flag (like std::atomic<bool>) which is checked by all threads (including the main thread). If set, then the sub-threads exit, and the main thread starts to join the sub-threads. Then you can exit cleanly.

If you use std::thread for the threads, that's a possible reason for the crashes you have. You must join the thread before the std::thread object is destructed.