Why is my program printing garbage?

依然范特西╮ 提交于 2020-01-01 14:20:30

问题


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 ?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/34710027/why-is-my-program-printing-garbage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!