dimanche 3 avril 2022

Why the code snippet gets stuck when optimization is enabled?

There are two question about the code snippet below.

  1. When the macro(i.e. NO_STUCK_WITH_OPTIMIZATION ) is not enabled, why this code snippet gets stuck when the optimization is enabled(i.e. -O1, -O2 or -O3) whereas the program works well if the optimization is not enabled?

  2. And why the program no longer get stuck if std::this_thread::sleep_for() is added?

     #include <functional>
     #include <thread>
     #include <iostream>
     #include <chrono>
     #include <atomic>
    
     #ifdef NO_STUCK_WITH_OPTIMIZATION 
     using TYPE = std::atomic<int>;
     #else
     using TYPE = int;  //The progrom gets stuck if the optimization is enabled.
     #endif
    
     int main()
     {
         TYPE is_run{1};
         auto thread = std::thread([&is_run](){while(1==is_run){
               //std::this_thread::sleep_for(std::chrono::milliseconds(10)); //If this line is added, the program is no longer gets stuck. Why?
                                             }
             std::cout << "thread game over" << std::endl;
         });
    
         std::this_thread::sleep_for(std::chrono::seconds(1));
         is_run = 0;
         thread.join();
     }
    

Aucun commentaire:

Enregistrer un commentaire