即使在满足条件后,While 循环也不会中断,但如果我在 while 循环中使用 "printf",则相同的代码开始工作

While loop does not break even after the condition is satisfied, but same code starts working if I use a "printf" in the while loop

我先说明一下情况:

  1. 这是一个菜单驱动的程序,其中选择的选项会一直执行,直到输入其他选项
  2. 选项通过 USB 端口提供给微控制器,ISR 调用处理输入命令解析的函数
  3. 程序只要输入进入无限while循环的选项就可以正常运行
  4. 进入死循环后,即使输入停止程序的命令也无法退出
  5. 程序确实进入了 ISR,即使它正在执行 while 循环,正如在 ISR 中使用 printf 所检查的那样。
  6. 当在 ISR 中遇到停止程序的命令时,它会设置由 while 循环检查的标志。
  7. 现在是奇怪的部分。如果我在 while 循环中插入 printf("%u",command),相同的代码开始工作。

sudo代码如下:

ISR_USB()
{
    char command=read_from_buffer();
    printf("Entered ISR and command = %c",command); // Prints on serial port and confirms the program entered ISR 
    if(command==STOP_DEMO)
        FLAG_TO_BREAK_WHILE=true;
    printf("%u",FLAG_TO_BREAK_WHILE); // Confirms correct value of flag is set
    command_parser(command);
 }

 command_parser(command)
{
    if(command=='1')
         printf("HELLO WORLD");
    else if(command=='2')
    {
        printf("While started");
        while(!FLAG_TO_BREAK_WHILE); // Gets stuck here 
        /*
         starts working if the above while is replaced by :
         while(!FLAG_TO_BREAK_WHILE)
         {
          printf("%u",FLAG_TO_BREAK_WHILE);
          }
        */
    }
    else if (command=='3')
        printf("stop command executed");
}

请帮助我了解这里的情况和这种行为。

注意:解析器在另一个文件中,变量被外部化。

正在发生的事情是 while(!FLAG) 正在优化为

if(!FLAG)
{
    while(true)
    {
         //do stuff
    }
}

要解决此问题,请将标志定义为易变的,编译器将在您的代码每次访问该标志时强制从内存中读取该标志。