zoukankan      html  css  js  c++  java
  • AutoMutex

    Android里的C++代码经常会看到AutoMutex _l(mLock);

    AutoMutex其实就是Thread的一种自动的互斥锁,定义在framework/base/include/utils/thread.h中;

    /*
    * Automatic mutex.  Declare one of these at the top of a function.
    * When the function returns, it will go out of scope, and release the
    * mutex.
    */
    typedef Mutex::Autolock AutoMutex;

    Autolock是Mutex的内嵌类(Java叫内部类),

    // Manages the mutex automatically. It'll be locked when Autolock is
    // constructed and released when Autolock goes out of scope.
    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;
    };

    看红色部分的注释就明白了,在函数代码中使用 AutoMutex 就可以锁定对象,而代码执行完AutoMutex所在的代码域之后,就自动释放锁,它的原理是充分的利用了c++的构造和析构函数~

  • 相关阅读:
    装饰器模式
    java构建树形节点优化
    excel操作
    回调函数
    网络编程
    小练习-接口发布文章 验证未登录
    requests模块
    try异常处理
    内置函数
    接口-用户登录,返回session
  • 原文地址:https://www.cnblogs.com/flyme/p/2181418.html
Copyright © 2011-2022 走看看