我正在寻找一种(多平台)方法来为我的 C++ 程序进行非阻塞控制台输入,这样我就可以在程序持续运行时处理用户命令。该程序还将同时输出信息。
最好/最简单的方法是什么?只要它们使用许可许可证,我就可以使用诸如 boost 之类的外部库。
原文由 Doug 发布,翻译遵循 CC BY-SA 4.0 许可协议
我正在寻找一种(多平台)方法来为我的 C++ 程序进行非阻塞控制台输入,这样我就可以在程序持续运行时处理用户命令。该程序还将同时输出信息。
最好/最简单的方法是什么?只要它们使用许可许可证,我就可以使用诸如 boost 之类的外部库。
原文由 Doug 发布,翻译遵循 CC BY-SA 4.0 许可协议
为什么不使用承诺?
#include <iostream>
#include <istream>
#include <thread>
#include <future>
#include <chrono>
void UIThread(std::chrono::duration<int> timeout) {
std::promise<bool> p;
std::thread uiWorker([&p]() {
bool running = true;
while(running) {
std::string input;
std::cin >> input;
if(input == "quit") {
p.set_value(true);
running = false;
}
}
});
auto future = p.get_future();
if (future.wait_for(timeout) != std::future_status::ready) {
std::cout << "UI thread timed out" << std::endl;
uiWorker.detach();
return;
}
uiWorker.join();
}
int main()
{
std::thread uiThread(UIThread, std::chrono::seconds(3));
std::cout << "Waiting for UI thread to complete" << std::endl;
uiThread.join();
}
原文由 yasinh 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.2k 阅读✓ 已解决
1 回答3.2k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.4k 阅读
我会通过创建单独的线程来调用正常的阻塞 IO 函数并传递给它一个回调函数,当它得到输入时它会调用它。你确定你需要做你说你想做的事吗?
至于同时输出信息,如果用户正在输入一些输入并且你打印了一些东西会发生什么?