【发布时间】:2017-02-22 15:32:14
【问题描述】:
我启动了两个线程,thread t1 正在等待通过cin 输入。我可以将EOF 之类的东西从thread t2 放入cin 以阻止cin 阅读吗?我试过'\n' 和ios::eofbit。两者都不起作用。
#include <thread>
#include <iostream>
#include <string>
#include <condition_variable>
std::condition_variable cv;
void Foo()
{
std::string sFoo;
std::cin >> sFoo;
// Do stuff with sFoo
}
void Bar()
{
// Do stuff
// If a condition is fullfilled I don't need the input in Foo anymore and so I want to cancel cin.
std::cin.setstate(std::ios::setstate(std::ios::eofbit); // Does not work
std::cin.putback('\n'); // Does not work
// maybe something similar like these above
}
int main()
{
std::thread t1(Foo);
std::thread t2(Bar);
}
【问题讨论】:
-
@KerrekSB 没有 cin.close() 函数...如果我错了请纠正我
-
你是对的,没关系:-S
-
@Mario 试试
::close( STDIN_FILENO );或::fclose( stdin );甚至::close( 0 );。见stackoverflow.com/questions/288062/…有点过激了…… -
您可以构建逻辑,如果 thread1 读取特定内容,则它可以退出。现在 thread2 可以
putback特定的东西以便 thread1 退出。看这个例子(cplusplus.com/reference/istream/istream/putback) -
@sameerkn 那么还是存在用户必须按回车键才能关闭cin读取的问题。
标签: c++ multithreading c++11 cin