C++ 如何在C+中接收输入时停止异步函数的执行+;
正如标题所述,我正在用标准库测试一些东西,我对如何确保何时接收到准确的输入感到困惑。我的代码如下所示:C++ 如何在C+中接收输入时停止异步函数的执行+;,c++,multithreading,asynchronous,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 << Wo
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;
}
static bool s_cinGet=false;
std::字符串循环字(std::向量字)
{
无符号整数i=0;
而(!s_cinGet)
{
系统(“cls”);
std::cout正如@PeteBecker所建议的,将s_cinGet
从bool
更改为std::atomic
可以消除未定义的行为。问题已解决。尝试将循环过程打印到另一个控制台\具有不同文本的同一控制台。然后查看这些单词是否相同。代码从一个控制台写入s_cinGet
线程并在另一个线程中读取。这意味着程序的行为未定义。将s_cinGet
的类型从bool
更改为std::atomic
,以消除该问题。没有将此作为问题的答案发布,因为问题中确实没有问题。@PeteBecker谢谢,我很感激。我我知道程序的行为是未定义的,如何改变它是我的全部问题,老实说,你的解决方案是有意义的。