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++ 线程有什么我不明白的地方还是这是一个实际问题?提前致谢