信号会中断主线程还是从某个 OS 线程调用?换句话说,在实现信号处理程序时我是否必须担心线程安全?例如,如果on_sigint
在单独的线程上调用以下代码,则会随机失败。他们是吗?会吗?
#include <csignal>
#include <windows.h>
HANDLE hSigint;
void on_sigint(int sig)
{
if (hSigint != NULL) SetEvent(hSigint);
else hSigint = INVALID_HANDLE_VALUE;
}
int wmain(int argc, wchar_t** argv)
{
hSigint = NULL;
signal(SIGINT, on_sigint);
BuildSomething();
if (hSigint == NULL)
{
hSigint = CreateEvent(NULL, TRUE, FALSE, NULL);
SetSomethingInMotion();
WaitForSingleObject(hSigint, INFINITE);
}
TearSomethingDown();
return 0;
}
尽管有 Windows 示例,Linux 的答案也很受欢迎。