【发布时间】: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<bool>以消除该问题。没有将此作为问题的答案发布,因为问题中确实没有问题。 -
@PeteBecker 谢谢,我很感激。我知道程序的行为是未定义的,如何改变它是我的全部问题,老实说,你的解决方案是有意义的。
标签: c++ multithreading asynchronous