Giffyguy
Giffyguy

Reputation: 21302

In C++, is it possible to detect the unexpected termination of a thread?

I have a background worker thread which is constantly processing data.
(created using std::thread)

If the thread runs out of data to process, the thread is designed to wait - and then resume when mote data becomes available for processing.
(using std::condition_variable)

If this thread ever terminates unexpectedly, I want to ensure the thread is restarted in a fresh state.

But I don't know how to detect thread termination, or react to it.
What's the best way to approach this scenario?

Upvotes: 1

Views: 825

Answers (1)

Serge
Serge

Reputation: 12384

Threads can only exit in a controlled way: either the thread itself decides to exit, or it gets cancelled from another thread. The only other possibility is a crash in your program or some external killer event.

Situation changes if you run different processes, not threads. In this case yes, the process could exit unexpectedly and you need to figure out how to find out if its exists.

If you expect that some coding in your thread can cause unexpected exit, you might just instantiate a guarding class with a destructor. The latter can do something to notify your system that the thread exists:

 struct Watchdog {
     ~WatchDog() {
          restartMe();
     }
  };

  void start() {
     WatchDog watcher;
     ...
   }

You might try to restart your thread from the destructor, or just notify yet another watcher thread that you need to restart this one.

Of cause, for separate processes you would need an absolutely different approach, i.e. heartbit pings, or whatever.

Upvotes: 1

Related Questions