为什么我的程序打印垃圾? [英] Why is my program printing garbage?

查看:50
本文介绍了为什么我的程序打印垃圾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码:

#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;
}

我创建了一个 thread 以降序打印数字,而 main 以升序打印.

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 ?

推荐答案

两个线程同时输出,从而打乱了你的输出.打印部分需要某种线程同步机制.

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

有关使用 此答案w/cpp/thread/mutex" rel="nofollow noreferrer">std::mutex 结合 std::lock_guard 用于 cout.

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

这篇关于为什么我的程序打印垃圾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆