c++ - 如何检查条件是否为真 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
}
但我认为必须有更好的方法来实现这一点。
我也想知道“睡眠”功能,但似乎这会暂停程序继续执行其他操作,而不是达到我想要的效果?
解决方案
您的情况只能发生在:
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;
}
推荐阅读
- html - 如何阻止文本在过渡中移动?
- javascript - CSS Body 最小高度无限滚动
- featuretools - 如果我们不指定,DFS 是否采用默认原语?
- ios - 复选框在 iPad 上不可点击 - XCUITest Apple
- cocos2d-x - Python无法检测文件,抛出错误
- c# - 如何使用一个连接显式加载多个 DbSet?
- ibm-cloud-private - 等待配置calico节点到节点mesh-ICP 2.1.0.2安装
- linux - 以太网连接在重启时断开,在 Linux VM(虚拟机)上
- angularjs - tether-shepherd 与 Angular 版本 1.7.0 不兼容
- python - 在 Python 中创建和组合大量图像 - 错误:打开的文件过多: