首页 > 解决方案 > C++ 控制台应用程序异步接受用户输入

问题描述

我最近偶然发现了这个 链接,我只是尝试了一下,但它并没有像我预期的那样工作。

使用此代码:

#include <atomic>
#include <thread>
#include <iostream>

void ReadCin(std::atomic<bool>& run)
{
    std::string buffer;

    while (run.load())
    {
        std::cin >> buffer;
        if (buffer == "q")
        {
            run.store(false);
        }
    }
}

int main()
{
    std::atomic<bool> run(true);
    std::thread cinThread(ReadCin, std::ref(run));

    while (run.load())
    {
        // some lengthy operation
    }

    run.store(false);
    cinThread.join();

    return 0;
}

在主 While 循环中,我有一个类的对象正在执行一些冗长的操作,我试图用来自用户的字母“q”来停止它。当我输入“q”时,我看到了“run.store(false);” 命中 ReadCin 方法,但这并没有让我脱离主 while 循环。我究竟做错了什么?

标签: multithreadingc++11

解决方案


推荐阅读