Boost -- scoped_lock v. S. mutex lock/unlock -- why is scoped_lock recommended?

Source: Internet
Author: User

Why is scoped_lock recommended?

 

This is the same reason as raiI idiom is becoming popular: You can indeed pack mutex that will be unlocked when you leave the execution range in any case.

Note: not only do you forget to call unlock (): After Your mutex is locked, an exception may also be thrown. The unlock CALL statement you write may never be executed, even inLock ()AndThe same is true if no return statement is returned between unlock ()..

M. lock () // M is a mutex //... foo (); // If throw is up in this function, your mutex will be locked forever //... m. unlock ()

YourScoped_lockThe Destructor is always automatically called when the stack is expanded. This ensures that the associated mutex is always released.

{Boost: scoped_lock lock (m); // M is a mutex //... foo (); // If throw is up, your raiI wrapper will unlock mutex //...}

In addition, this will increase the readability of your code. You do not need to add an unlock before each return statement.

Boost -- scoped_lock v. S. mutex lock/unlock -- why is scoped_lock recommended?

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.