c++ - 无需暂停代码的用户输入(C++ 控制台应用程序)

标签 c++ multithreading console-application user-input cin

如何在不导致代码停止执行的情况下进行输入?在过去的 20 分钟里,我一直在寻找答案,但没有结果。

cin >> string; 暂停代码 AFAIK。

我需要使用多线程,还是有更好的方法? (我什至不知道多线程是否可行。)

我最近开始学习c++,至少可以说我是初学者,所以请详细解释并包括我可能需要的任何库,谢谢。

最佳答案

这是一个示例,说明如何使用 >>> 与另一个使用多线程的调用并行地从标准输入流中读取 token 。

#include <iostream>
#include <thread>
#include <future>

int main() {
    // Enable standard literals as 2s and ""s.
    using namespace std::literals;

    // Execute lambda asyncronously.
    auto f = std::async(std::launch::async, [] {
        auto s = ""s;
        if (std::cin >> s) return s;
    });

    // Continue execution in main thread.
    while(f.wait_for(2s) != std::future_status::ready) {
        std::cout << "still waiting..." << std::endl;
    }

    std::cout << "Input was: " << f.get() << std::endl;
}

此处调用std::async使用启动参数 std::launch::async在不同的线程上异步运行任务。 std::async 返回并行运行的任务句柄,称为 future。这个 future 可用于检查任务是否完成。任务的结果也可以从 std::future 返回。使用成员函数的对象 std::future::get .

我传递给 std::async 的任务很简单 lambda expression创建一个字符串,从流中读取一个标记到字符串中并返回它(""s 是 C++14 中引入的标准文字,它返回一个空的 std::string 对象)。

在调用 std::async 之后,主线程继续执行语句(与异步运行的任务并行)。在我的示例中,执行了一个 while 循环,它只是等待异步任务完成。注意 std::future::wait_for 的使用每次迭代只阻塞 2 秒。 std::future::wait_for 返回一个status,可以将其进行比较以检查任务是否完成。

最后调用 std::future::get 将返回异步运行任务的结果。如果我们没有等待任务完成,调用将阻塞直到结果准备好。

注意不要在主线程中也(并行地)读取标准输入,因为读取调用不是原子事务,数据可能会出现乱码。

关于c++ - 无需暂停代码的用户输入(C++ 控制台应用程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127073/

相关文章:

c++ - dlg 类中是否有 getdocument() 函数?

c++ - 使用 VS2012 安装 boost 1.52

c++ - 在 C++ 中替代 mktime

performance - 在 Jmeter 中减速的最佳方法是什么?

c# - 如何在 C# 中循环计数?

c++ - 试图合并两个排序的动态数组 - C++

c# - 使用静态方法寻找关于线程安全的建议到 'process' 类实例

multithreading - Scala 避免异步测试用例的线程休眠

c# - 将 RDLC 渲染为 pdf 输出控制台应用程序

c# - 调试时在 Visual Studio 中的 C# 应用程序和 C 控制台应用程序之间传递数据