2

I recently stumbled upon this link and I just tried it, but it's not working as I expect.

With this code:

#include <atomic>
#include <thread>
#include <iostream>

void ReadCin(std::atomic<bool>& run)
{
    std::string buffer;

    while (run.load())
    {
        std::cin >> buffer;
        if (buffer == "q")
        {
            run.store(false);
        }
    }
}

int main()
{
    std::atomic<bool> run(true);
    std::thread cinThread(ReadCin, std::ref(run));

    while (run.load())
    {
        // some lengthy operation
    }

    run.store(false);
    cinThread.join();

    return 0;
}

In the main While loop, I have an object of a class that is doing some lengthy operation, one which I'm trying to stop with the letter "q" coming from the user. When I type "q", i see the "run.store(false);" hit in the ReadCin method, but this doesn't break me off from the main while loop. What am I doing wrong?

3
  • Case, then add a break in that block. cplusplus.com/forum/beginner/159985 Commented Mar 21, 2019 at 22:16
  • Are you sure that your "some lengthy operation" is short enough to let the main while loop check the value of run? Maybe this operation is freezing the while loop, no? Commented Mar 22, 2019 at 14:27
  • Might want to look at signals. Ctrl+C is usually used to cancel a long running application (SIGINT is sent in this case). Commented Mar 22, 2019 at 22:10

0

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.