C++ 11中mutex和unique_lock的使用

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex
#include <sstream>

class testthread 
{
public:
    std::mutex m_mtx;           // mutex for critical section
    std::condition_variable condition; /*必须与unique_lock配合使用*/
    int kk;

public:
    void func()
    {
        char ss[16] = {0};
        kk = 0;
        std::stringstream buf;
        std::this_thread::get_id()._To_text(buf);
        unsigned int nId = 0;
        buf >> nId;

        {
            std::unique_lock<std::mutex> lk(m_mtx);//unique_lock()出作用域会自动解锁
            
            for (int i = 0; i < 9; ++i)
            {
                kk++;
                sprintf_s(ss, "[%d]%d,%d\n", nId, kk, i);
                std::cout << ss ;
                if (kk == 4)
                    condition.wait(lk);
            }
            
        }

        m_mtx.lock();
        for (int i = 0; i < 12; ++i)
        {
            kk++;
            sprintf_s(ss, "[%d]%d,%d\n", nId, kk,i);
            std::cout << ss ;
        }
        m_mtx.unlock();
    }
};

int main()
{
    testthread t1;
    testthread t2;
    std::thread th1(&testthread::func, &t1);
    std::thread th2(&testthread::func, &t2);
    
    while (true)
    {
        t1.m_mtx.lock();
        t1.kk = 0;
        t1.m_mtx.unlock();
        t1.condition.notify_all();
        std::this_thread::sleep_for(std::chrono::milliseconds(2));
    }
    
    th1.join();
    th2.join();
    
    return 0;
}


代码运行结果:
[14928]1,0
[13144]1,0
[14928]2,1
[13144]2,1
[14928]3,2
[13144]3,2
[14928]4,3
[13144]4,3
[14928]1,4
[14928]2,5
[14928]3,6
[14928]4,7
[14928]1,8
[14928]2,0
[14928]3,1
[14928]4,2
[14928]5,3
[14928]6,4
[14928]7,5
[14928]8,6
[14928]9,7
[14928]10,8
[14928]11,9
[14928]12,10
[14928]13,11

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值