阻止函数调用的超时,即如何在X秒后停止等待用户输入? [英] Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?

查看:124
本文介绍了阻止函数调用的超时,即如何在X秒后停止等待用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当询问用户输入时,我们需要调用阻塞函数,但我希望能够解除阻塞并在指定的超时(通常是几秒)后恢复。

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).

我该怎么做?

std::string s;
// blocking function call
std::cin >> s; // how can I resume operation after timeout duration has elapsed?


推荐答案

你无法做到你梦想的方式,至少不是在标准 C ++ 11中(仅使用标准化的C ++ 11函数)。您几乎需要一些操作系统支持,并且您隐含地想要一些事件循环(或使用一些多线程方法。

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有多路复用系统调用例如民意调查(2)(我肯定Windows,Android,MacOSX,......有类似的东西);但你最好使用像 ncurses Qt SFML (另请参见 POCO 框架)。

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).

详情比你想象的复杂得多,并且是特定于操作系统的(但是有些库是在几个操作系统上工作的框架)。另请参见& 回答并阅读 tty demystified 页面。请注意,终端通常是今天的一些抽象虚拟设备,但过去一直是一个复杂的设备(今天主要模仿)。

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).

并且不要忘记 cin 可能是其他的东西比一个终端。它可能(在POSIX系统上显着) pipe(7)(命令管道)或文件(重定向)。然后等待5秒可能毫无意义或无用。

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.

这篇关于阻止函数调用的超时,即如何在X秒后停止等待用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆