For*_*aia 5 c++ multithreading user-input blocking windows-8.1
我的程序有许多不同的线程处理不同的事情,其中之一处理用户输入。
其他线程没有太多阻止调用的方式,那些阻止调用的线程是基于网络的,因此在套接字关闭时将被中断或正常返回。
但是,用户线程可以调用std::cin以获取用户输入。这样做的效果是,当所有其他线程都死掉时,用户线程仍然在用户输入上受阻,并且只会在下一次给出输入时终止。
我有什么办法可以在阻止之前检查是否有任何用户输入要抓取?
我了解cin.peek()存在,但根据我的经验,如果没有任何要读的内容,它将阻止。假定我正确使用了它
我的代码基本上是一个无限循环,当另一个线程切换条件变量时停止该循环:
void doLoop()
{
while (running) //running is shared between all threads and all others die quickly when it is false. It's set to true before the threads are started
{
string input = "";
getline(cin, input);
//Handle Input
}
}
Run Code Online (Sandbox Code Playgroud)
我在Windows上使用VS2013,无法使用外部库。我一直在使用windows.h和std。
您可以做的是使用 future 来允许用户输入有时间限制的内容。然后您可以将此代码插入到主循环中
#include <iostream> // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds
#include <string>
using namespace std;
bool myAsyncGetline(string & result)
{
std::cout<<"Enter something within the time limit"<<endl;
getline(cin,result);
return true;
}
int main()
{
// call function asynchronously:
string res;
std::future<bool> fut = std::async (myAsyncGetline,res);
std::chrono::seconds span (20);
if (fut.wait_for(span)==std::future_status::timeout)
std::cout << "Too Late!";
else
cout<<"You entered "<<res<<" "<< endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这在 VS2012 中可用,因此您应该能够重现它。
输出是“工具迟到了!” 如果超时(20s)后 getline 仍然有效,否则输出结果。
我认为这比搞乱杀死线程更简单,因为如果达到时间限制,函数会自行停止。如果您需要帮助将其集成到现有代码中,请告诉我,我可以提供帮助。
| 归档时间: |
|
| 查看次数: |
1935 次 |
| 最近记录: |