xml*_*lmx 15 c c++ multithreading signals c++11
C和C++标准支持信号的概念.但是,C11标准表示无法在多线程环境中调用函数signal(),或者行为未定义.但我认为信号机制本质上适用于多线程环境.
引用C11标准7.14.1.1.7
"在多线程程序中使用此函数会导致未定义的行为.实现的行为就像没有库函数调用信号函数一样."
对此有何解释?
以下代码不言而喻.
#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();
}
Run Code Online (Sandbox Code Playgroud)
thi*_*ton 16
但我认为信号机制本质上适用于多线程环境.
我认为这句话是中心的误解.signal()是一种进程间通信的方法,而不是用于跨线程的方法.线程共享公共内存,因此可以通过互斥锁和控制结构进行通信.进程没有公共内存,必须使用某些显式通信结构signal()或文件系统.