You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++14:用原子布尔互斥时,信号处理器中使用条件变量是否安全?

信号处理器中使用std::condition_variable的安全性疑问

背景

默认情况下,在信号处理器中使用std::condition_variable并不安全。但根据信号安全相关文档提示,若能确保同一时间无其他信号被处理,或许存在可行的可能。

文档中有如下提示:

在调用不安全函数或操作信号处理器也会访问的全局数据时,在主程序中阻塞信号传递。

核心疑问

若使用std::atomic_bool确保同一时间仅运行一个信号处理流程,此时在信号处理器中使用condition variable是否安全?

示例简化代码

std::atomic_bool g_signalBlock; // global 

void handleSignal(int signalNumber, siginfo_t* signalInfo, void* ucontext) {
    if (g_signalBlock.exchange(true)) {
        return; // ignore this signal. another signal being processed.
    } else {
       // process the signal
       if (signalNumber == SIGUSR2) {
         // notify another thread using std::condition_variable
       } else {
         // re-raise non-SIGUSR2 signal (to exit the program) 
         signal(signalNumber, SIG_DFL);
         raise(signal);
       }

       g_signalBlock.store(false);  // now allow other signals
    }
}

使用场景说明

信号处理逻辑中部分异步信号安全操作耗时过长(如异步信号安全的文件日志),对于SIGABRT等会导致进程退出的信号尚可接受,但同一处理器还需处理SIGUSR2信号以记录线程轨迹,为避免影响其他线程,需将日志操作委托给后台线程。


内容的提问来源于stack exchange,提问作者RandomQuestion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 10:17:26