RAII 想到AutoLock,Mutex类和C++11中的unique_lock

RAII(Resource Acquisition Is Initialization)其定义直接引用The C++ Programming Language 4th Edition
“The technique of acquiring resources in a constructor and  releasing them in a destructor, known as Resource Acquisition Is  Initialization or RAII”

    我浅显的理解就是资源的获取(锁,数据库链接,文件等)和释放分别在构造函数和析构函数中实现。由此想到了之前的一篇文章C++简洁实现线程安全单例类里面的两个类:AutoLock和Mutex,它们就是典型的RAII类,Mutex的构造函数中init了一个mutex,析构函数中则destroy了它,AutoLock在构造函数中获得了一个mutex,在析构函数中则释放了它,看代码就了然。

#define DISABLE_COPY_AND_ASSIGN(T) \  
        T(const T &); \  
        T& operator=(const T &)  
struct Recursive {};
class Mutex {  
public:  
    Mutex() {  
        pthread_mutex_init(&_mutex, NULL);  
    }  
    explicit Mutex(Recursive) {
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP);
        pthread_mutex_init(&_mutex, &attr);
        pthread_mutexattr_destroy(&attr);
    }
    ~Mutex() {  
        pthread_mutex_destroy(&_mutex);  
    }  
      
    int lock() {  
        return pthread_mutex_lock(&_mutex);  
    }  
      
    int trylock() {  
        return pthread_mutex_trylock(&_mutex);  
    }  
      
    int unlock() {  
        return pthread_mutex_unlock(&_mutex);  
    }  
      
private:  
    pthread_mutex_t _mutex;  
    // RAII class should not be able to be copied
    DISABLE_COPY_AND_ASSIGN(Mutex); 
};  
  
template <class T>  
class AutoLock {  
public:  
    explicit AutoLock(T* t) : _t(t) {  
        _t.lock();  
    }  
    ~AutoLock() {  
        _t.unlock();  
    }  
private:  
    T* _t;  
    // RAII class should not be able to be copied
    DISABLE_COPY_AND_ASSIGN(AutoLock);  
};  
    其实在C++11中的std::mutex和std::unique_lock已经实现了上述两个类的功能,引用The C++ Programming Language 4th Edition中的代码:

mutex m; // used to protect access to shared data
// ...
void f()
{
	unique_lock<mutex> lck {m}; // acquire the mutex m
	// ... manipulate shared data ...
}

书中的解释是:

A thread will not proceed until lck’s constructor has acquired its mutex, m (§5.3.4). 

The corresponding destructor releases the resource. So, in this example, unique_lock’s destructor 

releases the mutex when the thread of control leaves f() (through a return, by “falling off the 

end of the function,” or through an exception throw).

This is an application of the “Resource Acquisition Is Initialization” technique (RAII; §3.2.1.2, §13.3). 

This technique is fundamental to the idiomatic handling of resources in C++. 

Containers (such as vector and map), string, and iostream manage their 

resources (such as file handles and buffers) similarly.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值