Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ signal handler can wake a thread?

Since a C++ signal handler should only access volatile std::sig_atomic_t or std::atomic(since C++11), is it possible to have a thread sleeping and wake with it?

std::atomic_bool exit_now(false);

void signal_handler(int signal)
{
  exit_now=true;
}

int main() {

      std::signal(SIGINT, signal_handler);

      A a;
      B b;

      a.RunAsync();
      b.RunAsync();

      while(!exit_now)
          std::this_thread::sleep_for(std::chrono::seconds(1));

      a.Stop();
      b.Stop();

      return 0;
}

In this case, A and B ::RunAsync() both do their business on other threads until I call ::Stop(), so my only option is to busy-wait on the main thread (with or without a predefined sleep period).

Ideally I would want the main thread to sleep until signaled, possibly with a condition variable, but that looks illegal to do.

like image 875
nunojpg Avatar asked Apr 20 '26 07:04

nunojpg


1 Answers

I would suggest (blocking the signals and) using sigwait(2) to synchronously wait for the signals in the main thread, then you completely circumvent the issue of having to communicate from a signal handler to a thread.

like image 76
Seg Fault Avatar answered Apr 21 '26 22:04

Seg Fault