c++ - 在C++中收到输入时如何停止执行异步功能

标签 c++ multithreading asynchronous

如标题所示,我正在用标准库测试某些东西,而我对如何确定何时收到准确的输入感到困惑。我的代码如下所示:

static bool s_cinGet = false;

std::string CycleWords(std::vector<std::string> Words)
{
    unsigned int i = 0;
    while (!s_cinGet)
    {
        system("cls");
        std::cout << Words[i] << std::endl;
        i++;
        i = i % Words.size();
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    if (i != 0) i--;
    else i = Words.size() - 1;
    return Words[i];
}

int main()
{
    std::vector<std::string> Words = { "Tunti", "Triliteral", "Carl" };

    while (true)
    {
        s_cinGet = false;
        auto future = std::async(CycleWords, Words);
        std::cin.get();
        s_cinGet = true;

        std::string word = future.get();

        //system("cls");
        std::cout << word << std::endl;
    }
    std::cin.get();
    return 0;
}

该程序非常简单。它会循环显示某些单词,直到用户按任意键并打印最后一个单词为止。我想确保当用户按下一个键时,最后一个单词是完全相同的单词。任何建议表示赞赏。

最佳答案

正如@PeteBecker所建议的那样,将s_cinGetbool更改为std::atomic<bool>摆脱了未定义的行为。问题解决了。

关于c++ - 在C++中收到输入时如何停止执行异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60381964/

相关文章:

c++ - 如何在 glReadPixels 为空时生成屏幕截图?

c++ - 如何计算对此函数的递归调用以及正确的答案是什么?

c++ - boost 线程池和进程之间的互斥量

c++ - 与锁相比,无论有无争用,原子/互锁变量的速度有多快?

javascript - 自定义 AJAX 表单无法异步工作

c++ - 如何安装 c++ 库以便我可以使用它?

c# - 线程安全的公共(public)字符串

c# - 在 ASP.NET 请求中使用 Mutex 类是否安全?

java - java中等待异步http请求

ios - 在代码周围包装 Async/Main Thread block