【问题标题】:Why is my program printing garbage?为什么我的程序打印垃圾?
【发布时间】:2016-04-15 01:59:06
【问题描述】:

我的代码:

#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。为什么我的代码打印垃圾?

【问题讨论】:

  • 我不知道你为什么不能访问它。这是一个公共要点。

标签: c++ multithreading synchronization


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    这不是“垃圾”——这是您要求的输出!它只是混乱了,因为您总共使用了 zero 同步机制来防止单个 std::cout &lt;&lt; ... &lt;&lt; std::endl 行(不是原子的)被类似的行(仍然不是原子的)打断另一个线程。

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

    【讨论】:

      猜你喜欢
      • 2018-02-18
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多