【问题标题】:How to stop execution of an async function when input is recieved in C++在 C++ 中接收到输入时如何停止执行异步函数
【发布时间】:2020-06-08 10:33:44
【问题描述】:

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

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;
}

这个程序真的很简单。它循环浏览一些单词,直到用户按下任何键并打印最后一个单词。我想确保用户按下一个键时最后一个单词是完全相同的单词。任何建议表示赞赏。

【问题讨论】:

  • 尝试将循环过程打印到另一个控制台\具有不同文本的相同控制台。然后看看那些词是不是一样的。
  • 代码从一个线程写入s_cinGet,并在另一个线程中读取。这意味着程序的行为是未定义的。将s_cinGet 的类型从bool 更改为std::atomic&lt;bool&gt; 以消除该问题。没有将此作为问题的答案发布,因为问题中确实没有问题。
  • @PeteBecker 谢谢,我很感激。我知道程序的行为是未定义的,如何改变它是我的全部问题,老实说,你的解决方案是有意义的。

标签: c++ multithreading asynchronous


【解决方案1】:

正如@PeteBecker 所建议的,将s_cinGetbool 更改为std::atomic&lt;bool&gt; 可以消除未定义的行为。问题解决了。

【讨论】:

    猜你喜欢
    • 2017-06-21
    • 1970-01-01
    • 2021-07-11
    • 2016-08-10
    • 2021-11-26
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多