本文介绍了volatile sig_atomic_t 的正确使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 this 站点,可以在信号处理程序中使用 volatile sig_atomic_t 类型的变量.现在我的问题是,例如下面的代码仍然是原子的,因此不会引入竞争条件吗?

According to this site, 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 甚至首先适用于多核系统,还是我们应该使用 C++11 的 atomic 来处理多核系统上的信号处理程序(EDIT:运行多线程程序)?

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 a;

static void signal_handler(int sig, siginfo_t *si, void *unused)
{
  int b;
  ................
  b = ...;
  a = a | b;
  ................
}

推荐答案

除非您的程序是多线程的,否则信号处理程序绝不会与您程序中的其他代码同时运行,当然它们也绝不会与它们中断的代码同时运行.只要信号 sig 在信号处理程序的持续时间内被屏蔽,您的代码就可以了.

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.

这篇关于volatile sig_atomic_t 的正确使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 02:38