Ank*_*ane 7 c++ timer sliding-window
我想在C++中实现超时功能.
如果用户未在2秒内输入该值,则程序必须显示超时语句并再次询问输入
EX(输出屏幕):
Timer=0;
Please enter the input: //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input: //if input is not given within 2 seconds then
Time-out: 2 seconds
Timer again set to 0
Please enter the input:22
Data accepted
Terminate the program`
Run Code Online (Sandbox Code Playgroud)
码:
#include<iostream>
#include<time.h>
using namespace std;
int main()
{
clock_t endwait;
endwait = 2000 ;
cout<<endwait;
while (clock() < endwait)
{
cout<<"Please enter the input:";
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我已经处理了上面的代码.但这只在进入WHILE循环时发生.我该如何做到这一点,以便获得所需的输出.
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
using namespace std;
condition_variable cv;
int value;
void read_value() {
cin >> value;
cv.notify_one();
}
int main()
{
cout << "Please enter the input: ";
thread th(read_value);
mutex mtx;
unique_lock<mutex> lck(mtx);
while (cv.wait_for(lck, chrono::seconds(2)) == cv_status::timeout)
{
cout << "\nTime-Out: 2 second:";
cout << "\nPlease enter the input:";
}
cout << "You entered: " << value << '\n';
th.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Please enter the input:
Time-Out: 2 second:
Please enter the input:
Time-Out: 2 second:
Please enter the input:22
You entered: 22
Run Code Online (Sandbox Code Playgroud)