使用C ++ condition_variable的“眨眼”可中断延迟

时间:2019-09-20 18:55:21

标签: c++

一个类存储程序的状态-准备好还是忙。准备就绪时,LED指示灯显示稳定的颜色,否则闪烁表示设备正忙。我希望指示灯“立即”反映程序状态的变化,即状态更改为就绪时,它不应尝试完成其闪烁周期。

在其自己的线程中运行的例程对该信息的作用如下:

using namespace std::chrono::literals;

// This runs in a thread ... only snippet given here 
while(!m_should_close) {
    if (!m_ready) {
        // Blink
        std::unique_lock<std::mutex> lk(m_needs_update_mtx);

        led_on();

        if(!m_needs_update_cv::wait_for(lk, 300ms, []{ return m_needs_update; })) continue;

        led_off();

        if(!m_needs_update_cv::wait_for(lk, 300ms, []{ return m_needs_update; })) continue;

    } else {
        // Steady on
        led_on();        
    }
}

m_needs_update atomic_boolean设置为true,以通知闪烁信号线程m_should_closem_ready发生了更改,并且m_needs_update_cv的类型为{{1 }}。我的设计有两个问题:

  1. 感觉不正确。关于用长线的“垃圾”来代替这两个延迟,有些令人费解。

  2. 有效期为600毫秒的计时器不是很准确,并且是Linux调度,争用等一时的想法。

您有什么建筑建议吗?谢谢。

0 个答案:

没有答案