Linux component Encapsulation (iv) Mutexlock auto-dissolve lock using RAII technology

Source: Internet
Author: User
Tags mutex

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.