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

SPV*_*SPV 4 c++ multithreading synchronization

我的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我创建一个thread按递减顺序打印数字,同时main按递增顺序打印.

此处输出示例.为什么我的代码打印垃圾?

Dan*_*_ds 11

两个线程同时输出,从而扰乱输出.您需要在打印部件上使用某种线程同步机制.

有关使用与for 结合使用的示例,请参阅此答案.std::mutexstd::lock_guardcout


Lig*_*ica 9

这不是"垃圾" - 这是你要求的输出!它只是乱七八糟,因为你已经使用了大量的同步机制来防止各个std::cout << ... << std::endl线(非原子线)被另一个线程中的类似线(它们仍然不是原子线)中断.

传统上我们会围绕每条线锁定一个互斥锁.