简体   繁体   中英

How to break std::cin(std::cin.getline) executuion from other thread

I have some code:

while(true) {
    std::string message;
    
    std::cin >> message; // break it
    
    // send message
  }

I want to interrupt waiting for user input from std::cin from other thread.
How can I do it? Thanks in advance!

std::cin is a blocking call that can not be interrupted.

This thread here seems to have some non-blocking alternatives: https://stackoverflow.com/a/40812107/2562287

If you used a non blocking alternative for std::cin along with an boolean (threadsafe from either a mutex or being atomic, preferably the latter), you could set the boolean on the other thread and read the boolean on the input thread, if the boolean is either true or false then exit the input function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM