We have written this code more than once:
{ mutex_. Lock (); // XXX if (....) return ; // XXX Mutex_.unlock ();}
Obviously, we forget about locks in this code. So how to prevent this, we adopt the same strategy as the smart pointer, the lock and unlock process is encapsulated in an object.
The implementation of "Object Lifetime" equals "lock period".
The code is as follows:
class mutexlockguard:noncopyable{public: &Mutex): mutex_ (Mutex) {mutex_. Lock (); } ~Mutexlockguard () {mutex_.unlock ();} Private : &Mutex_;};
The practice of putting resources in constructors and releasing resources into destructors is the RAII technique in C + +, " resource acquisition is initialization ". Its clever in C + + stack object is bound to be destructor, so resources will be released.
The benefits of this class for us to write elegant code are obvious, for example:
Const { mutex_. Lock (); int ret = queue_.size (); Mutex_.unlock (); return queue_.size ();}
This code is really not beautiful, but with Mutexlockguard, we can write:
Const { lock(mutex_); return queue_.size ();}
The aesthetics of the code has improved a lot.
Of course, there is a way to use the error, for example:
Const { mutexlockguard (mutex_); return queue_.size ();}
The lock cycle for this code is limited to that line, and to prevent the use of errors, we add a macro:
#define Mutexlockguard (M) "Error Mutexlockguard"
This can lead to compilation errors when used incorrectly, which leads us to identify problems earlier.
Linux component Encapsulation (iv) Mutexlock auto-dissolve lock using RAII technology