Linux volatile sig_atomic_t 的正确使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8488791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Proper usage of volatile sig_atomic_t
提问by MetallicPriest
According to thissite, one can use variables of type volatile sig_atomic_t
inside a signal handler. Now my question is, would for example something like the following code still be atomic and thus introduce no race conditions?
根据该站点,可以volatile sig_atomic_t
在信号处理程序中使用类型变量。现在我的问题是,例如下面的代码仍然是原子的,因此不会引入竞争条件吗?
Assume that we are using a multicore processor (EDIT: running a multithreaded program). Does volatile sig_atomic_t
even work for multicore systems in the first place or should we use the atomic<unsigned int>
of C++11 for signal handlers on a multicore system (EDIT: running a multithreaded program)?
假设我们使用的是多核处理器(编辑:运行多线程程序)。是否volatile sig_atomic_t
针对多核系统甚至工作摆在首位,或者我们应该使用atomic<unsigned int>
C ++ 11的信号处理程序在多核系统上(编辑:在运行多线程程序)?
volatile sig_atomic_t a;
static void signal_handler(int sig, siginfo_t *si, void *unused)
{
int b;
................
b = ...;
a = a | b;
................
}
回答by R.. GitHub STOP HELPING ICE
Unless your program is multithreaded, signal handlers never run concurrently with other code in your program, and they certainly never run concurrently with the code they've interrupted. Your code is fine as long as the signal sig
is masked for the duration of the signal handler.
除非您的程序是多线程的,否则信号处理程序永远不会与您程序中的其他代码同时运行,而且它们肯定永远不会与它们中断的代码同时运行。只要信号sig
在信号处理程序的持续时间内被屏蔽,您的代码就可以。