Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ console input blocks so i can't kill thread

My program has many different threads handling different things, and one of them deals with user input.

The other threads don't have much in the way of blocking calls, and those that do block are network based so will be interrupted or return gracefully when the socket is shut down.

However the user thread has calls to std::cin in order to grab the user input. The effect this has is while all the other threads are dead the user thread is still blocking on user input, and will only die the next time input is given.

Is there any way for me to check if there is any user input to grab before blocking?

I understand cin.peek() exists but from my experience, it blocks if there is nothing to read in. 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's set to true before the threads are started
    {
        string input = "";
        getline(cin, input);

        //Handle Input

    }
}

I'm on windows, using VS2013, and cannot use external libraries. I'm using windows.h and std throughout.

like image 212
Force Gaia Avatar asked Nov 09 '22 21:11

Force Gaia


1 Answers

I believe that the C++ Standard does not offer a way of checking the standard input without blocking. Since you are willing to use platform specific functions, 'kbhit()' might suit your needs but it has been deprecated in Windows. An alternative is offered, _kbhit(). Of course this is not portable to other platforms.

This is the link to MSDN: _kbhit

like image 90
imreal Avatar answered Nov 14 '22 23:11

imreal