C ++ console input blocks, so I can't kill a thread

My program has a lot of different threads handling different things, and one of them concerns user input.

Other threads do not have a special way of blocking calls, and those that make the block are network-based, will be interrupted or will return gracefully when the socket is disconnected.

However, the user stream has calls std::cinto capture user input. The effect that this has is that all other threads are dead, the user thread still blocks the user’s input and will only die on the next time input.

Is there a way to check if there is any user input to capture before locking?

I understand that it cin.peek()exists, but from my experience it is blocked if there is nothing to read. Assuming I'm using it correctly

My code is basically an infinite loop that stops when another thread switches the condition variable:

void doLoop()
{
    while (running) //running is shared between all threads and all others die quickly when it is false. It set to true before the threads are started
    {
        string input = "";
        getline(cin, input);

        //Handle Input

    }
}

I am in windows using VS2013 and cannot use external libraries. I use windows.h and std everywhere.

+4
source share
2 answers

What you can do is use futures to allow the user to enter something with a time limit. Then you can insert this code in your main loop

#include <iostream>       // std::cout
#include <future>         // std::async, std::future
#include <chrono>         // std::chrono::milliseconds
#include <string>
using namespace std;


bool myAsyncGetline(string & result)
{
    std::cout<<"Enter something within the time limit"<<endl;
    getline(cin,result);
    return true;
}

int main()
{
  // call function asynchronously:
  string res;
  std::future<bool> fut = std::async (myAsyncGetline,res); 


  std::chrono::seconds span (20);
  if (fut.wait_for(span)==std::future_status::timeout)
    std::cout << "Too Late!";
  else
      cout<<"You entered "<<res<<" "<< endl;

  return 0;
}

This is available in VS2012 so you can play it.

" !". getline (20 ), .

, , , , . , , , .

0

, ++ . , "kbhit()" , Windows. _kbhit(). , .

MSDN: _ kbhit

+1

Source: https://habr.com/ru/post/1569454/


All Articles