【问题标题】:How to differentiate alarm signal of different threads?如何区分不同线程的报警信号?
【发布时间】:2014-09-09 10:20:23
【问题描述】:

我必须实现用户级线程库。我的问题是睡眠功能。

我正在唤醒一个使用 ualarm 函数生成的 SIGALRM 信号休眠的线程。 当多个线程以不同的睡眠时间设置为睡眠时,我如何确定计时器何时触发我必须从睡眠队列中删除哪个线程......?? 如何区分不同线程的告警信号??

【问题讨论】:

    标签: multithreading thread-sleep


    【解决方案1】:

    信号处理程序是从目标线程的上下文中调用的。因此,特定于线程的存储按预期工作(我在 Linux 和 Solaris 上对其进行了测试)。从信号处理程序使用the unix self-pipe 技巧从信号处理程序返回到线程:

    __thread int signal_pipe; // The write end.
    
    extern "C" void signal_handler(int signo, siginfo_t*, void*)
    {
        if(!signal_pipe) // programming error: signal is being delivered to a wrong thread.
            abort();
        unsigned char signo_byte = static_cast<unsigned>(signo);
        // standard unix self pipe trick
        write(signal_pipe, &signo_byte, 1);
    }
    

    使用此信号处理程序的每个线程都必须创建自己的管道并使用该管道的写入端初始化signal_pipe

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多