为什么我的程序打印垃圾?

Why is my program printing garbage?

我的代码:

#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 以递增顺序打印。

样本输出here。为什么我的代码打印垃圾?

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

参见 this answer for an example using a std::mutex combined with std::lock_guard cout

这不是 "garbage" — 这是您要求的输出!它只是混乱了,因为您总共使用了 同步机制来防止单个 std::cout << ... << std::endl 行(不是原子的)被类似的行(它们是仍然不是原子的)在另一个线程中。

传统上我们会在每一行周围锁定一个 mutex