标签: cthreads

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

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

c++ multithreading pthreads c++17 cthreads

3
推荐指数
1
解决办法
50
查看次数

标签 统计

c++ ×1

c++17 ×1

cthreads ×1

multithreading ×1

pthreads ×1