码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-09-17 12:53:35      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:mes   ios   stream   性能   join()   unique   eth   provided   cal   

#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;
}

 

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

标签:mes   ios   stream   性能   join()   unique   eth   provided   cal   

原文地址:https://www.cnblogs.com/bitsstitcher/p/11532619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!