2

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

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;
}
starball
  • 20,030
  • 7
  • 43
  • 238
Julia.T
  • 129
  • 2
  • 10

1 Answers1

2

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);
    }
}
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • 3
    The function `std::exit` is intended for C code and calling it in C++ is generally not recommended, because the destructor for automatic variables on the stack (generally local variables) will not be called. See this question for further information: [How to end C++ code](https://stackoverflow.com/q/30250934/12149471). However, I cannot think of any obviously better solution in this case. – Andreas Wenzel Mar 10 '23 at 11:09