当涉及循环时,Cpp 线程无法按预期工作

Ash*_*sad 3 c++ multithreading pthreads c++17 cthreads

C++ sleep_for 方法未按预期工作。我正在尝试编写一个打印 1 到 10 的程序,但每次打印之间有一些时间间隔。

1 (1 秒后) 2 (1 秒后) 3 . 。。等等。

代码是:

#include <iostream>
#include <thread>
#include <chrono>


void produce()
{
    for(int i=0;i<10;i++)
    {
        std::cout<<i+1<<" ";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    std::cout<<"\n";
}


int main()
{
    std::cout<<"Starting the thread\n";
    std::thread thread1(produce);
    thread1.join();
    std::cout<<"Thread finished execution\n";
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上述程序的输出是:

等待 10 秒....然后立即从 1 打印到 10。(为什么会发生这种情况?)

如果我将生产方法更改为:

void produce()
{
    for(int i=0;i<10;i++)
    {
        std::cout<<i+1<<" ";
        std::this_thread::sleep_for(std::chrono::seconds(1));
        std::cout<<"\n";
    }
    
}
Run Code Online (Sandbox Code Playgroud)

然后,我得到了预期的结果(我所做的就是将 cout 放入循环中,它使程序在打印下一个数字之前等待一秒钟。

关于 C++ 线程有什么我不明白的地方还是这是一个实际问题?提前致谢

Sam*_*hik 7

无论如何,这与线程无关。

  std::cout<<i+1<<" ";
Run Code Online (Sandbox Code Playgroud)

a 上的格式化输出操作std::ostream被缓冲。现在它位于cout的内部缓冲区中,等待写入更多内容,直到可以将其全部写出一大块,和/或直到出现换行符。

  std::cout<<"\n";
Run Code Online (Sandbox Code Playgroud)

像这样。正如您自己发现的那样。

如果没有换行符,您需要自己明确地刷新它:

  std::cout<<i+1<<" "<<std::flush;
Run Code Online (Sandbox Code Playgroud)