The C and C++ standards support the concept of signal. However, the C11 standard says that the function signal() cannot be called in multi-threaded environments, or the behavior is undefined. But I think the signal mechanism is by nature for multi-threaded environments.
A quote from the C11 standard 7.14.1.1.7
"Use of this function in a multi-threaded program results in undefined behavior. The
implementation shall behave as if no library function calls the signal function."
Any explanations about this?
The following code is self-evident.
#include <thread>
#include <csignal>
using namespace std;
void SignalHandler(int)
{
// Which thread context here?
}
void f()
{
//
// Running in another thread context.
//
raise(SIGINT); // Is this call safe?
}
int main()
{
//
// Register the signal handler in main thread context.
//
signal(SIGINT, SignalHandler);
thread(f).join();
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…