Example
#include <csignal>
#include <cstdio>
#include <cstdlib>
volatile std::sig_atomic_t gSignalStatus = 0;
void signal_handler(int signal) {
gSignalStatus = signal;
}
int main() {
// Install a signal handler
std::signal(SIGTERM, signal_handler);
while (gSignalStatus == 0) {}
printf("%d\n", gSignalStatus);
}
I am trying to understand few things:
- Is it even correct to declare a variable with a type of
std::sig_atomic_t
withoutvolatile
? Given the variable is shared between the handler and a thread -- just likegSignalStatus
above but withoutvolatile
. According to the answer of this post, it seemsvolatile
is required. - According to C++ standard:
extern "C" void atomic_signal_fence(memory_order order) noexcept; 6 Effects: Equivalent to atomic_thread_fence(order), except that the resulting ordering constraints are established only between a thread and a signal handler executed in the same thread.
it sounds like the specification assumes the signal handler can be called by any thread and so atomic_signal_fence
is added to the spec? But the quoted spec above also mentions "same thread". Hence, I am confused. Tho, on my machine, the signal handler is called by the main thread. An example to illustrate the need of atomic_signal_fence
would be nice too!
Thanks!
Aucun commentaire:
Enregistrer un commentaire