Why is my program printing garbage?

My code is:

#include <iostream>
#include <thread>

void function_1()
{
    std::cout << "Thread t1 started!\n";
    for (int j=0; j>-100; j--) {
        std::cout << "t1 says: " << j << "\n";
    }
}

int main()
{
    std::thread t1(function_1); // t1 starts running

    for (int i=0; i<100; i++) {
        std::cout << "from main: " << i << "\n";
    }

    t1.join(); // main thread waits for t1 to finish
    return 0;
}

I create threadone that prints numbers in descending order, and mainprints in ascending order.

Sample output here . Why is my code printing garbage?

+4
source share
2 answers

Both streams are output simultaneously, thereby scrambling your output. You will need some kind of thread synchronization mechanism on the print part. A.

See this answer for an example, using std::mutexin conjunction with std::lock_guardfor cout.

+11
source

"" — , ! , , std::cout << ... << std::endl ( ) ( ) .

.

+9

Source: https://habr.com/ru/post/1623670/


All Articles