Tunti
Tunti

Reputation: 109

How to stop execution of an async function when input is recieved in C++

As title states i'm testing some stuff with standard library and i got confused on how to make sure when exactly input was recieved. My code looks like this:

static bool s_cinGet = false;

std::string CycleWords(std::vector<std::string> Words)
{
    unsigned int i = 0;
    while (!s_cinGet)
    {
        system("cls");
        std::cout << Words[i] << std::endl;
        i++;
        i = i % Words.size();
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    if (i != 0) i--;
    else i = Words.size() - 1;
    return Words[i];
}

int main()
{
    std::vector<std::string> Words = { "Tunti", "Triliteral", "Carl" };

    while (true)
    {
        s_cinGet = false;
        auto future = std::async(CycleWords, Words);
        std::cin.get();
        s_cinGet = true;

        std::string word = future.get();

        //system("cls");
        std::cout << word << std::endl;
    }
    std::cin.get();
    return 0;
}

The program is really simple. It cycles through some words till user presses any key and prints the last word. I want to make sure that the last word was exactly the same word when the user pressed a key. Any suggestions are appreciated.

Upvotes: 1

Views: 218

Answers (1)

Tunti
Tunti

Reputation: 109

As @PeteBecker suggested, changing s_cinGet from bool to std::atomic<bool> gets rid of undefined behaviour. Problem solved.

Upvotes: 2

Related Questions