When asking the user for input we need to call a blocking function, but I want to be able to "unblock" and resume after a specified timeout has elapsed (usually some seconds).
How can I do this?
std::string s;
// blocking function call
std::cin >> s; // how can I resume operation after timeout duration has elapsed?
You cannot do the way you dream, at least not in standard C++11 (using only standardized C++11 functions). You practically need some operating system support, and you implicitly want some event loop (or use some multi-threading approach).
However, you could use your operating system facilities and/or some external libraries.
FWIW, Linux has multiplexing syscalls such as poll(2) (and I am sure that Windows, Android, MacOSX, .... have similar things); but you'll much better use libraries like ncurses or Qt or SFML (see also POCO framework).
Details are considerably more complex than what you imagine, and are operating system specific (but some libraries are frameworks working on several operating systems). See also this & that answers and read the tty demystified page. Be aware that "terminal" is usually today some abstract virtual device, but in the past have been a complex device (which is mostly emulated today).
And don't forget that
cin
might be something else than a terminal. It might be (on POSIX systems notably) a pipe(7) (command pipeline) or a file (redirection). Then waiting for 5 seconds might be meaningless or useless.You can write a program with
main()
which creates 2 processes sayprocess1()
andprocess2()
usingfork()
function.In
process1()
take Input form user.In
process2()
make a delay ofX
seconds as you say and then terminate the process1 via process2.