0

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!

User98
  • 31
  • 6
  • 1
    You can't. You need to think of a different solution to whatever your ultimate problem is. – molbdnilo Nov 04 '20 at 12:16
  • Please explain to us why this is a problem. What occurs and why do you want to change it? – JHBonarius Nov 04 '20 at 12:20
  • @JHBonarius, it's loop for typing and sending messages to server. I want to break this loop if connection with server closed – User98 Nov 04 '20 at 12:26

1 Answers1

0

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.

Lily
  • 1,386
  • 2
  • 13
  • 16