c++11 lock_guard用法

1 篇文章 0 订阅
1 篇文章 0 订阅

相比于mutex功能,lock_guard具有创建时加锁,析构时解锁的功能,类似于智能指针,为了防止在线程使用mutex加锁后异常退出导致死锁的问题,建议使用lock_guard代替mutex。下面利用代码演示功能:

// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
//c++11 thread
#include "stdafx.h"
#include<thread>
#include<mutex>
#include<iostream>

using namespace std;
using namespace std::this_thread;
using namespace std::chrono;

void ThreadFun1();
void ThreadFun2();
int tickets = 100;
mutex tex;
int main()
{
    thread t1(ThreadFun1);
    thread t2(ThreadFun2);
    t1.join();
    t2.join();

    return 0;
}
void ThreadFun1()
{
    while (tickets > 0)
    {
        sleep_for(seconds(1));
        lock_guard<mutex> lck(tex);
        //tex.lock();
        if (tickets > 0)
        {
            if (tickets < 96) {
                cout << "A thread exit \n";
                return;
            }
                
            cout <<"A thread sell tickets:" << tickets-- <<endl;
        }
        //tex.unlock();
    }
}
void ThreadFun2()
{
    while (tickets > 0)
    {
        sleep_for(seconds(1));
        lock_guard<mutex> lck(tex);
        //tex.lock();
        if (tickets > 0)
        {
            cout <<"B thread sell tickets:" << tickets-- <<endl;
        }
        //tex.unlock();
    }
}

在A线程异常退出后,lock_guard自动解锁,使得B线程可以进行执行,若调用mutex,会使得B线程一直等待。

  • 7
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值