为什么 Visual Studio 2019 年 std:cout 中没有竞争条件?

Why no race conditions in std:cout in Visual Studio 2019?

我想向朋友展示一个基于 std:cout 作为共享资源的简单竞争条件示例,如 this article 中所述。

因此,我在全新的 Visual Studio 2019 控制台应用程序中输入了以下代码:

#include <iostream>
#include <string>
#include <thread>

using namespace std;

void CallHome(string message)
{
    cout << "Thread " << this_thread::get_id() << " says " << message << endl;
}

int main()
{
    thread t1(CallHome, "Hello from Jupiter");
    thread t2(CallHome, "Hello from Pluto");
    thread t3(CallHome, "Hello from Moon");
    CallHome("Hello from Main/Earth");
    thread t4(CallHome, "Hello from Uranus");
    thread t5(CallHome, "Hello from Neptune");
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    return 0;
}

根据 Visual Studio 2015 年的文章及其屏幕截图,我预计输出文本会被来自不同线程的交错片段弄乱。

但是,我的程序的每个 运行 始终得到以下输出:

Thread 1472 says Hello from Main/Earth
Thread 15112 says Hello from Jupiter
Thread 9248 says Hello from Neptune
Thread 17876 says Hello from Pluto
Thread 18452 says Hello from Uranus
Thread 18088 says Hello from Moon

那里发生了什么事? C++ 运行time 最近发生了什么变化?是不是与线程或 std:cout 有关的东西现在使它摆脱了竞争条件?

我将 void CallHome(string message) 更改为每个线程打印消息 100 次,

void CallHome(string message)
{
    for (int i = 0; i < 100; ++i)
        cout << "Thread " << this_thread::get_id() << " says " << message << endl;
}

我收到了以下消息。

Thread 10588 says Hello from Uranus
Thread 10588 says Hello from Uranus
Thread 10588 says Thread 8116 says Hello from Neptune
Hello from Uranus
Thread 10588 says Hello from Uranus

可以在许多线程试图获取共享资源的地方发现竞争条件。试了5次太少了,无法检查。