Why is my program printing garbage?

2020-07-18 05:05发布

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 ?

2条回答
霸刀☆藐视天下
2楼-- · 2020-07-18 05:49

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.

查看更多
该账号已被封号
3楼-- · 2020-07-18 05:53

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.

查看更多
登录 后发表回答