[英]How to stop, from another thread, std::cin from reading anymore input?
我啟動了兩個線程, thread t1
正在等待通過cin
輸入。 我可以把類似的EOF
位cin
從thread t2
停止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);
}
我不認為有來自istream的標准非阻塞讀取或中斷等待輸入的線程的方法。 您可能會嘗試查看boost asio或增強iostreams - 也許他們有這個功能。
您可以在POSIX系統或其他系統上的對應系統上使用select / poll來檢查是否有任何數據可用,或使用某種形式的中斷讀取 - API也取決於系統。
下面是一個有效的臟解決方案 - 你最終得到一個泄漏的線程,它將永遠等待stdin,但它會做你想要的。
#include <thread>
#include <iostream>
#include <string>
#include <condition_variable>
#include <chrono>
#include <mutex>
#include <queue>
std::mutex m;
bool dataEnd = false;
std::queue<std::string> data;
std::condition_variable sAvail;
void Reader() {
while (std::cin) {
auto s = std::string();
std::cin >> s;
auto lock = std::unique_lock<std::mutex>(m);
data.push(std::move(s));
sAvail.notify_all();
}
}
void Foo() {
for (;;) {
auto lock = std::unique_lock<std::mutex>(m);
if (data.empty()) {
sAvail.wait(lock);
if (dataEnd) {
std::cerr << "No more data!\n";
break;
}
}
if (!data.empty()) {
auto s = std::move(data.front());
data.pop();
std::cerr << "Got " << s << '\n';
}
}
}
void Bar(std::thread& reader) {
// Do stuff
// If a condition is fullfilled I don't need the input in Foo anymore and so I want to cancel cin.
{
auto lock = std::unique_lock<std::mutex>(m);
dataEnd = true;
sAvail.notify_all();
reader.detach();
}
// maybe something similar like these above
}
int main() {
std::thread r(Reader);
std::thread t1(Foo);
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
std::thread t2(Bar, std::ref(r));
t1.join();
t2.join();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.