终端输入超时(线程+定时器+cin)



我想启动一个控制台程序(qt,c++(,并询问用户是否要加载以前的设置或设置新的设置。10秒后没有输入,我想自动加载设置。

我的方法:

  • 使用qTimer和一个附加线程启动程序
  • 通过std::cin询问用户在附加线程中的输入
  • 如果没有退出线程并继续主程序的输入,则启动计时器

我面临的问题是,我无法以编程方式中止std::cin。即使退出线程也不会中止std::cin。

所以我想我的方法是不对的,实现我的总体目标的最佳方式是什么?

根据您提到的线程,我猜其目的是允许用户在控制台提示下输入文本,而不阻塞Qt事件循环。在这种情况下,您可能可以通过使用QSocketNotifier来避免显式地同时使用线程。

以下示例演示了。。。

#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <QCoreApplication>
#include <QSocketNotifier>
#include <QTimer>
int
main (int argc, char **argv)
{
try {
QCoreApplication app(argc, argv);
QTimer timeout;
/*
* Create a QSocketNotifier and let it monitor stdin/std::cin.  The
* connected lambda just reads one char at a time here.
*/
QSocketNotifier stdin_notifier(::fileno(stdin), QSocketNotifier::Read);
QObject::connect(&stdin_notifier, &QSocketNotifier::activated,
[&](QSocketDescriptor socket, QSocketNotifier::Type type)
{
/*
* We've received input so stop the timer and read a
* single char.
*/
timeout.stop();
char c;
::read(::fileno(stdin), &c, 1);
std::cout << "stdin: read `" << c << "'n";
});
/*
* Start with a 5 second timeout.
*/
unsigned remaining = 5;
std::cout << "you have " << remaining << "s to start entering textr" << std::flush;
QObject::connect(&timeout, &QTimer::timeout,
[&]
{
if (!--remaining) {
std::cout << std::left << std::setfill(' ') << std::setw(50)
<< "too late" << "n";
app.quit();
} else {
std::cout << "you have " << remaining
<< "s to start entering textr" << std::flush;
}
});
timeout.start(1000);
exit(app.exec());
}
catch (std::exception &ex) {
std::cerr << ex.what() << "n";
}
catch (...) {
std::cerr << "unrecognized exceptionn";
}
exit(1);
}

最新更新