C++11之 unique_lock和lock_guard避免死锁

#include <iostream>
#include <fstream>
#include <thread>
#include <mutex>
#include <string>

using namespace std;

class LogFile {
public:
    LogFile() {
        f.open("log.txt");
    }

    ~LogFile() {
    }

    void shared_print(string msg, int id) {
        lock_guard<mutex> guard(mu);
        f<<msg<<id<<endl;
    }

    // Never return f to the outside world
    ofstream& getStream() { return f;}
    // Never pass f as an augument to user provided function
    void processf(void fun(ofstream&)) {
            fun(f);
    }

private:
    ofstream f;
    mutex mu;
};

void function_1(LogFile& log) {
    for(int i = 0; i >-100; i--) {
        log.shared_print("From t1: ",i);
    }
}

int main()
{
    LogFile log;
    thread t1(function_1,ref(log));

    for(int i= 0; i < 100; i++) {
        log.shared_print("From main: ",i);
    }

    t1.join();

    return 0;
}

当需要同时申请多把锁的时候,使用如下两种方式
lock(mtx1,mtx2)
lock_guard(mtx1,adopt_lock)
lock_guard(mtx2,adopt_lock)

unique_lock lock1(mtx1,defer_lock)
unique_lock lock2(mtx2,defer_lock)
lock(lock1,lock2)


unique_lock VS lock_guard
lock_guard 不允许手动unlock/lock  性能消耗小
unique_lock更加灵活, 允许手动多次 unlock/lock  性能消耗大

void foo() {
    unique_lock<mutex> locker(mtx,defer_lock);  defer_lock假定还没有上锁
    // do something not using mtx
    mtx.lock(); 
    // do something using mtx to protect
    mtx.unlock();
    // do something else
}

Lazy Initialization

#include <iostream>
#include <thread>
#include <mutex>
#include <fstream>
#include <string>

using namespace std;

class LogFile {
private:
    ofstream f;
    mutex _mu;
    mutex _mu_open;
public:
    void shared_print(string& msg, int id) {
        {
            unique_lock<mutex> open_lck(_mu_open);
            if(!f.is_open()) {
                f.open("log.txt");
            }
        }

        unique_lock<mutex> locker(_mu);

        // do other things

    }
};


class LazyInitializationLogFile {
private:
    ofstream f;
    mutex _mu;
    once_flag _flag;
public:
    void shared_print(string7 msg, int id) {
        call_once(_flag,[&](){f.open("log.txt");});

        unique_lock<mutex> locker(_mu);

        // do other things
    }
}

int main()
{
    return 0;
}

 

转载于:https://www.cnblogs.com/bitsstitcher/p/11532619.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值