我有一个调用 std::getline(std::cin,input) 的线程和另一个每 x 分钟唤醒一次并检查状态的线程。如果状态为 True,我的整个 C++ 应用程序需要终止/关闭。问题是 getline() 是一个阻塞调用,当我将 loop_status 设置为 true 时,它仍然不会停止,因为 getline() 正在阻塞。如何退出调用 getInput() 的线程?
std::atomic<bool> loop_status{false}
//在线程1中调用 getInput(){
while(!loop_status){
std::string input;
getline(std::cin,input);
print(input);
}
}
//在线程 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;
}
std::exit(EXIT_SUCCESS)
就足够了,例如:
while(!loop_status){
std::this_thread::sleep_for(chrono::milliseconds(5000));
//check some status
if(some_status){
std::exit(EXIT_SUCCESS);
}
}