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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM