Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send input on std::cin

I'm running a program with a main thread and a secondary one, and, after a certain codition is met both should exit. Problem is the secondary thread, after checking the run condition is still valid waits for user input using std::cin, so if the condition is met after that call to std::cin, the thread keeps on waiting for user input. The code is something like this:

MainThread()
{
    std::thread t1{DoOtherWork}
    ...
    while(condition)
    {
         DoWork();
    }

    t1.join();
}

DoOtherWork()
{
    while(condition)
    {
         char c;
         std::cin >> c;
         ProcessInput(c);
    }

    return;
}

So, when condition is not met anymore, both should exit, but the program is stuck on waiting for user input. If I just enter any random character and press enter, the program then exits fine.

My question is if there is any way from the main thread, before joining the secondary thread, to send some input to std::cin, so that the other thread will continue the execution and exit without any further user input. Thanks in advance

like image 966
Mdp11 Avatar asked Nov 07 '22 02:11

Mdp11


1 Answers

Here is a cross-platform solution:

The trick is to create a third thread, whose one and only job is to receive input. Once processed, the input is recorded. The second thread can access these records asynchronously at any interval desired using a mutex. This eliminates the blocking nature of std::cin and allows you to terminate the thread whenever.

On Windows, you can use CreateThread instead of std::thread. It returns a handle that you can use with TerminateThread to terminate the given thread at any point.

like image 68
Hi - I love SO Avatar answered Nov 15 '22 06:11

Hi - I love SO