Hacker News new | ask | show | jobs
by TeMPOraL 1777 days ago
That only makes sense if units of your code run in a loop and communicate asynchronously :). But, if you want a simple supervisor pattern in C++, then... try/catch block is your supervisor, exceptions are how your process dies. Consider:

  template<typename Fn>
  auto CallWithSupervision(Fn fn) -> decltype(fn()) {
    // supervision loop
    // configure conditions as needed
    while(true) {
      try {
        return fn();
      }
      catch(std::exception& e) {
        // log failure details
      }
      catch(...) {
        // optional: exceptions out of handled set?
        // kill supervisor.
        throw;
      }
    }
  }

  //elsewhere
  CallWithSupervision([relevant=state,&nd=captures]() { return Client(relevant, nd); });
Modify as you see fit. It's the simplest, synchronous Erlang supervisor, in C++. And it will already work with your code - exception handling is very composable this way.
1 comments

Except it isn't robust.

Exceptions occur when "Very Bad No Good Undefined Horrible Things" have (at last, been found to have) happened.

So if you have no guarantee that the memory space is uncorrupted, you have no guarantee that all resources have been recovered, you have no guarantee that in attempting to deallocated resources that they have been allocated in the first place. (Read the fine fine print on exceptions in constructors and destructors.) TL;DR; Don't do that. But exceptions are what happen when people do what they shouldn't.