是否可以设置std :: cin的超时? [英] Is it possible to set timeout for std::cin?

查看:172
本文介绍了是否可以设置std :: cin的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以设置std :: cin的超时?
例如,std :: cin在10秒内没有收到任何数据 - 它抛出异常或返回错误。

Is it possible to set timeout for std::cin? For example, std::cin doesn't receive any data during 10 seconds - it throws an exception or returns an error.

已编辑:

定价从 Boost库?据我所知,它是便携式图书馆。是否可能要求Boost库的计时器在预定义的时间段后抛出异常?

And what about timer from Boost library? As far as I know, it is portable library. Is it possible to ask timer of Boost library to throw exceptions after predefined period of time? I guess it can solve this problem.

推荐答案

不能为设置超时, std :: cin 。即使在使用非便携式技术时,这样做也并不简单:您需要替换 std :: cin 的流缓冲区。

It isn't possible to set a time out for std::cin in a portable way. Even when resorting to non-portable techniques, it isn't entirely trivial to do so: you will need to replace std::cin's stream buffer.

在UNIX系统上,我将用 std :: cin 替换由默认流缓冲区使用的文件描述符 0 来读取输入。要实际读取输入,我将使用 poll()来检测输入的存在,并在此函数上设置超时。根据 poll()的结果,我将读取可用的输入或失败。为了可能处理未转发到文件描述符的键入的字符,但也可以合理地关闭缓冲,直到输入换行符。

On a UNIX system I would replace the default stream buffer used by std::cin by a custom one which uses file descriptor 0 to read the input. To actually read the input I would use poll() to detect presence of input and set a timeout on this function. Depending on the result of poll() I would either read the available input or fail. To possibly cope with typed characters which aren't forwarded to the file descriptor, yet, it may be reasonable to also turn off the buffering done until a newline is entered.

当使用多个线程时,可以创建一个可移植的过滤流缓冲区,它使用线程读取实际数据,另一个线程使用一个定时条件变量,等待第一个线程发出信号表示接收到数据或超时时间到期。注意,您需要防止虚假唤醒,以确保在没有输入时确实达到了超时。这将避免不得不修改从 std :: cin 读取数据的实际方式,尽管它仍然替换 std :: cin使用的流缓冲区,以便通过此名称访问此功能。

When using multiple threads you can create a portable filtering stream buffer which uses on thread to read the actual data and another thread to use a timed condition variable waiting either for the first thread to signal that it received data or for the time out to expire. Note that you need to guard against spurious wake-ups to make sure that the timeout is indeed reached when there is no input. This would avoid having to tinker with the actual way data is read from std::cin although it still replaces the stream buffer used by std::cin to make the functionality accessible via this name.

这篇关于是否可以设置std :: cin的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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