非阻塞控制台输入 C

新手上路,请多包涵

我正在寻找一种(多平台)方法来为我的 C++ 程序进行非阻塞控制台输入,这样我就可以在程序持续运行时处理用户命令。该程序还将同时输出信息。

最好/最简单的方法是什么?只要它们使用许可许可证,我就可以使用诸如 boost 之类的外部库。

原文由 Doug 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

我会通过创建单独的线程来调用正常的阻塞 IO 函数并传递给它一个回调函数,当它得到输入时它会调用它。你确定你需要做你说你想做的事吗?

至于同时输出信息,如果用户正在输入一些输入并且你打印了一些东西会发生什么?

原文由 Seth Carnegie 发布,翻译遵循 CC BY-SA 3.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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题