Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cleanly exit a threaded C++ program?

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?

like image 589
rjlion795 Avatar asked Apr 18 '18 06:04

rjlion795


People also ask

How do you exit a thread?

To end the thread, just return from that function. According to this, you can also call thread. exit() , which will throw an exception that will end the thread silently. thread.

How do I stop multithreading?

Once you detect new messages, you handle the first message from the queue (or handle all messages currently in the queue, depending on how you set things up). Try to avoid nested message loops (message loops within event handlers) as my practical experience is that they turn into a mess.

What happens to threads on exit?

Exiting the main thread will not result in the process exiting if there are any other threads still active. According to the old-fashioned model of how processes exit, a process was in control of all its threads and could mediate the shutdown of those threads, thereby controlling the shutdown of the process.


1 Answers

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.

like image 165
Some programmer dude Avatar answered Sep 21 '22 16:09

Some programmer dude