Using a signal listener thread – how do I stop it?

  c++, multithreading, pthreads, signals

A snippet from my main method:

  std::atomic_bool runflag;
  // ...
  std::thread signaller([&]() mutable {
    while (runflag) {
      int sig;
      int rcode = sigwait(&set, &sig);
      if (rcode == 0) {
        switch (sig) {
          case SIGINT: {
            // handle ^C
          }
        }
      }
    }
  });
  
  while (runflag) {
    next = cin.get();
    // handle character input
  }
  signaller.join();

I’m using the sigwait()-based approach for detecting SIGINT sent from the command line.

The signaller thread uses sigwait() to listen for signals. The program terminates when runflag is set false. However, the signaller thread will still be blocked at sigwait when this happens. I don’t think I can use condition variables, as sigwait has no way to hook into one. Is there an alternative solution that is preferably not Linux-only?

EDIT 1: Alternatively, is there an interruptible version of sigwait?

Source: Windows Questions C++

LEAVE A COMMENT