'How to use Sleep() in two threads at the same time while they are both outputting something? (C++)

I want to output text on two separate lines in the console at the same time. I made the write() function which does an animation, like a typewriter when outputting the string passed as a parameter, with the time delay, also a parameter. I made another function which changes the cursor position, changeColumnLine().

The program is made for Windows and nothing else.

The problem is that right now it outputs, without the animation, this:

  dog
cat

(it also waits the length of the word * time before outputting this, which does output at the same time)

And it should output, letter by letter, on two separate lines dog and cat at the same time.

This is the basic write() function:

void write(string word, int time, int line)

    {
        for (int i = 0; i < word.length(); i++)
        {
            //changeColumnLine(i, line);
            cout << word.at(i);
            Sleep(time);
        }
        cout << "\n";
    }

And this is the one I made in hopes of fixing it when using threads (using C++ 20):

void write(string word, int time, int line)
{
    osyncstream syncout{ std::cout };
    for (int i = 0; i < word.length(); i++)
    {
        changeColumnLine(i, line);
        //this_thread::sleep_for(200ms); 
        syncout << word.at(i);
        //Sleep(time);
    }
    syncout << "\n";
}

This is the changeColumnLine() that I wrote:

void changeColumnLine(int pos_line, int pos_column)
{
    HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
    int x_pos = pos_line;
    int y_pos = pos_column;
    COORD screen;
    HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    screen.X = x_pos;
    screen.Y = y_pos;
    SetConsoleCursorPosition(hOutput, screen);
}

And this is the main() function:

int main()
{
    thread t1(write, "cat", 200, 1);
    thread t2(write, "dog", 200, 5);
    t1.join();
    t2.join();
    return 0;
}

This problem has been giving me a headache the past 3 days and I just seem to not be able to find an answer.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source