通过sleep_for来使线程睡眠一定的时间

本文展示了一个使用C++标准库中的线程和互斥锁进行同步的例子。两个线程分别打印计数,通过互斥锁保证数据的一致性。此示例有助于理解如何在C++中实现多线程间的同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
int main()
{
    mutex m;
    thread t1([&m]()
    {
        this_thread::sleep_for(chrono::seconds(10));//通过sleep_for来使线程睡眠一定的时间
        for (int i = 0; i < 10; i++)
        {
            m.lock();
            cout << "In t1 ThreadID:" << this_thread::get_id() << ":" << i << endl;
            m.unlock();
        }
    });
    thread t2([&m]()
    {
        this_thread::sleep_for(chrono::seconds(1));//由于线程t1睡眠的时间较长,t2先执行了
        for (int i = 0; i < 10;i++)
        {
            m.lock();
            cout << "In t2 ThreadID:" << this_thread::get_id() << ":" << i << endl;
            m.unlock();
        }
    });
    t1.join();
    t2.join();
    cout << "Main Thread" << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值