gpt4 book ai didi

c++ - 如何从另一个线程停止 std::cin 不再读取输入?

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:53 26 4
gpt4 key购买 nike

我启动了两个线程,线程 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);
}

最佳答案

我不认为有标准的非阻塞从 istream 读取或中断等待输入的线程的方法。您可能会尝试查看 boost asio 或 boost iostreams - 也许它们具有此功能。

您可以在 POSIX 系统或其他系统上使用 select/poll 来检查是否有任何数据可用,或者使用某种形式的中断读取 - API 也依赖于系统。

下面是一个可行的肮脏解决方案——你最终会得到一个泄漏的线程,它将永远等待标准输入,但它会做你想做的。

#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();
}

关于c++ - 如何从另一个线程停止 std::cin 不再读取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com