5

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

2
  • Is this helpful? non-blocking std::getline, exit if no input I haven't read the solution in detail, but it seems to accept input asynchronously, and the thread can end itself. Commented Mar 16, 2021 at 11:50
  • If this is for linux you can use signals API to unblock it, namely pthread_kill/sigaction, I used this a few times in C, I imagine in C++ it's roughly the same. Commented Mar 16, 2021 at 12:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I would like to use a platform independent solution
@Mdp11 Edited with a cross-platform solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.