首页 > 解决方案 > 如何检查条件是否为真 5 秒?

问题描述

我想检查一个条件是否在 5 秒内保持为真,如果是,则执行一个操作。

就像是...

while(1){
    // other code here
    if( cond1 == cond2 ){
        (start 5 second timer){
            timerFinished = true;
        }
    } else {
        reset timer;
    }
    // rest of code
}

我确实想知道这样的事情是否会起作用......

while(1){
    long myTimer = 0;
    if( cond1 == cond2 ){
        myTimer = myTimer + 1;
    } else {
        myTimer = 0;
    }

    if( myTimer > 100000 ){ //arbitary figure equivalent to 5 seconds in program cycles
        timerFinished = true;
    }
    // rest of code
}

但我认为必须有更好的方法来实现这一点。

我也想知道“睡眠”功能,但似乎这会暂停程序继续执行其他操作,而不是达到我想要的效果?

标签: c++

解决方案


您的情况只能发生在:

1)多线程环境:单线程环境不会发生状态变化。请参阅下面的代码片段来实现这样的场景。

2) 外部硬件触发: 使用边沿电平变化触发的硬件中断,无需轮询。

atomic<bool> cond;

bool PressedFor5Sec() {

    auto start = chrono::high_resolution_clock::now();

    bool flag = true;
    while (chrono::high_resolution_clock::now() < start + chrono::seconds(5)) {
        if (!cond) {
            flag = false;
            break;
        }
        this_thread::sleep_for(chrono::milliseconds(10));
    }
    return flag;
}

int main() {
    cond = true; // initial state

    auto simulator = thread([]() {
        this_thread::sleep_for(chrono::seconds(3)); // state change time delay
        //this_thread::sleep_for(chrono::seconds(6));
        cond = false; // state change 
    });

    bool result = PressedFor5Sec();

    cout << (result ? " Pressed for 5 sec" : " Press interrupted") << endl;

    simulator.join();
    return 0;
}

推荐阅读