Automutex in Android

Source: Internet
Author: User

In the startthreadpool () function of frameworks/base/libs/binder/processstate. cpp,

The function was declared at the beginning:

Automutex _ L (mlock );

It's not complicated, but I feel very thoughtful.

In frameworks/base/include/utils/Threads. h, there are:

Class mutex {...... class autolock {public: inline autolock (mutex & mutex): mlock (mutex) {mlock. lock ();} inline autolock (mutex * mutex): mlock (* mutex) {mlock. lock ();} inline ~ Autolock () {mlock. Unlock () ;}private: mutex & mlock ;};......}; typedef mutex: autolock automutex;

We can see that mlock. Lock () is locked in the constructor and mlock. Unlock () is unlocked in the destructor.
Therefore, for a function to be locked, we only need to declare the automutex _ L (mlock) variable at the beginning of the function, and it will lock,
When the function exits, a temporary variable will be parsed and unlocked.

Really clever !!!

Object-oriented is really a subtle learning.
I remembered that I had defined an object that generates a random number and used seed in the constructor to prevent the result of selecting seed for every function call.
Because the latter has the same seed every time, the re-generated random number is the same.

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.