2016-01-10 97 views
4

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

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

我同时为了提高打印main递减的顺序创建thread,打印数量。

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

+0

我不确定你为什么不能访问它。这是一个公众的主旨。 – SPV

回答

11

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

有关使用std::mutexstd::lock_guard组合cout的示例,请参阅this answer

9

这不是“垃圾”—它是你要求的输出!它只是混乱起来,因为您已经使用了总计同步机制来防止其他线程(不是原子的)中的单个行被其他线程中的类似行中断(这些行不是原子的)。

传统上我们会锁定一个互斥体围绕每一行。