【问题标题】:multi-threads in c++11? [duplicate]c++11中的多线程? [复制]
【发布时间】:2014-01-23 12:27:07
【问题描述】:

好的,我正在使用 Mac 学习 c++11 中的多线程。据我所知,所有线程都是同时执行的。我从here找到以下代码

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::thread

void foo() 
{
    std::cout << "\nIn foo \n";
}

void bar(int x)
{
    std::cout << "\nIn bar \n";
}

int main() 
{
    std::thread first (foo);     // spawn new thread that calls foo()
    std::thread second (bar,0);  // spawn new thread that calls bar(0)

    std::cout << "main, foo and bar now execute concurrently...\n";

    // synchronize threads:
     first.join();                // pauses until first finishes
    second.join();               // pauses until second finishes

    std::cout << "foo and bar completed.\n";

    return 0;
} 

每次我运行代码时,我都会得到以下示例的奇怪结果

aIIinnn ,bf aofroo o

和 bar 现在同时执行... foo 和 bar 已完成。

我错过了什么?

【问题讨论】:

  • 这不是链接答案的副本。尽管有标题,但这里的 OP 并没有询问关于 std::cout 的一般性问题:他询问的是可以导致特定答案的特定问题(实际上是在结束之前提出的问题)。不应该作为重复关闭。至少不像以前那样。

标签: c++ multithreading c++11


【解决方案1】:

您正在同时从两个线程通过std::cout 打印。虽然这显然不是数据竞争,因此是“安全的”[*],但它的输出——如你所见——并不是特别有意义。您可能希望使用std::mutex 来限制访问,或者使用提供更强保证的 IO 库。

[*] 除非你打电话给std::cout.sync_with_stdio(false)

【讨论】:

    【解决方案2】:

    这是因为两个线程同时在标准输出 std::out 上写入。您将需要添加线程同步机制(互斥体、信号量等)以确保一次只有一个线程写入 std::out。您面临的问题是由于线程彼此并行运行,这就是它们的目的。搜索互斥量或信号量并将它们集成到您的代码中,您将解决问题。

    如果您多次运行当前代码,您会看到每次执行代码时结果都会有所不同,或者至少在大多数情况下会有所不同。

    【讨论】:

      【解决方案3】:

      代码有两部分。第一部分是thread firstthread secondmain 同时运行(即同时)。因此,"\n In foo \n""\n In bar \n""main, foo and bar now execute concurrently...\n" 的打印将同时发生,因此输出将是它们的随机混合(更正式地,称为racing)。

      也就是说,第一部分打印了OP中提到的“随机输出”,即"\n In foo \n""\n In bar \n""main, foo and bar now execute concurrently...\n"的shuffle。

      在第一部分之后,主线程将暂停,直到第一个线程和第二个线程完成(称为synchronization)。因此,"foo and bar completed.\n" 的打印将始终生成准确的输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        相关资源
        最近更新 更多