Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my program printing garbage?

My code:

#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 a thread that prints numbers in decreasing order while main prints in increasing order.

Sample output here. Why is my code printing garbage ?

like image 427
spv Avatar asked Nov 30 '22 23:11

spv


2 Answers

Both threads are outputting at the same time, thereby scrambling your output. You need some kind of thread synchronization mechanism on the printing part.

See this answer for an example using a std::mutex combined with std::lock_guard for cout.

like image 168
Danny_ds Avatar answered Dec 15 '22 22:12

Danny_ds


It's not "garbage" — it's the output you asked for! It's just jumbled up, because you have used a grand total of zero synchronisation mechanisms to prevent individual std::cout << ... << std::endl lines (which are not atomic) from being interrupted by similar lines (which are still not atomic) in the other thread.

Traditionally we'd lock a mutex around each of those lines.

like image 20
Lightness Races in Orbit Avatar answered Dec 15 '22 23:12

Lightness Races in Orbit