是的std ::信号和std ::提高线程安全的? [英] Are std::signal and std::raise thread-safe?

查看:181
本文介绍了是的std ::信号和std ::提高线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C和C ++标准支持信号的概念。但是,C11的标准说,函数信号()不能在多线程环境中调用,或者行为是不确定的。但我认为信号机制本质上是多线程的环境。

从C11标准的A报价7.14.1.1.7


  

在不确定的行为多线程程序的结果该函数的使用。该
  实现应表现为,如果没有库函数调用信号的功能。


这个任何解释?

以下code是不言而喻的。

 的#include<螺纹>
#包括LT&;&csignal GT;使用命名空间std;无效SignalHandler(INT)
{
    //哪个线程上下文在这里?
}无效F()
{
    //
    //运行在另一个线程的上下文。
    //
    提高(SIGINT); //这是调用安全吗?
}诠释的main()
{
    //
    //注册在主线程上下文信号处理程序。
    //
    信号(SIGINT,SignalHandler);    螺纹(F)。加入();
}


解决方案

  

但我认为信号机制本质上是多线程的环境中。


我觉得这句话是中央的误解。 信号()是一个方法间的处理的通信,而不是接口的线程的。线程共享共同的记忆,因此可以通过互斥体和控制结构进行通信。进程没有共同的记忆,并与像一些明确的通信结构信号()或文件系统必须做出-做的。

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();
}

解决方案

But I think the signal mechanism is by nature for multi-threaded environments.

I think this sentence is the central misunderstanding. signal() is a method for inter-process communication, not for inter-thread. Threads share common memory and can therefore communicate via mutexes and control structures. Processes don't have common memory and must make-do with some explicit communication structures like signal() or the filesystem.

这篇关于是的std ::信号和std ::提高线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆