Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stop all c++ threads

I have a thread that is calling std::getline(std::cin,input) and another thread that wakes up every x mins and checks a status. If the status is True my whole c++ application needs to terminate/shutdown. Problem is getline() is a blocking call and when I set loop_status to true it still wont stop since getline() is blocking. How can I exit the thread calling the getInput()?

std::atomic<bool> loop_status{false}

//called in thread 1
getInput(){

    while(!loop_status){
          std::string input;
          getline(std::cin,input);
          print(input);
    
    }
}

//called in thread 2

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

check(){

   while(!loop_status){

       std::this_thread::sleep_for(chrono::milliseconds(5000));
      //check some status 

       if(some_status){

          loop_status=true;

       }


   }

}


main(){


thread t1(getInput());
thread t2(check);

t1.join();
t2.join();
  


return 0;
}

>Solution :

Simply calling std::exit(EXIT_SUCCESS) should suffice, for example:

while(!loop_status){
    std::this_thread::sleep_for(chrono::milliseconds(5000));
    //check some status 
    if(some_status){
        std::exit(EXIT_SUCCESS);
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading