How to use a timer in C++ to force input within a given time?
#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;
}
Output:
Please enter the input:
Time-Out: 2 second:
Please enter the input:
Time-Out: 2 second:
Please enter the input:22
You entered: 22
I think there is no need to use complex code (multithreading or mutex) for this purpose. See the code below :
#include <iostream>
#include <time.h>
#include <conio.h>
using namespace std;
int main()
{
int numInput;
clock_t start = clock();
cout << "Timer: 2 sec"<<endl;
cout << "Please enter the input: ";
while ( ! _kbhit() ) //Check for keyboard hit
{
//Check if 2 sec timer expired or not
if (((clock () - start)/ CLOCKS_PER_SEC ) >= 2)
{
cout << "\nTimeout 2 sec . . ." << endl;
cout << "Please enter the input: ";
start = clock(); //Set new timer
}
}
//Get the input here
cin >> numInput;
cout << "Data accepted: " << numInput << endl;
_getch();
return 0;
}
I am afraid, it is not possible in a standard way because I/O operations will block, by default, the calling process until it's finalized or an error is encountered.
You could work it around by creating a thread which checks whether the input has been completed and go sleeping, if needed. But that's not really practical.
The issue lies in the abstraction iostream
/FILE
s give you: you don't have access to the underlying source, the one the OS "understands" as well and therefore capable to give you that kind of functionality (namely, I/O polling).