【C++】Android中的同步机制

在涉及多线程、多进程编程时,同步问题是不可避免的。在不同的操作系统或者项目中,都有自独特的同步手法,不过同步原理基本相同。在Android系统中,封装了几个同步类,下面来看一下这些同步类的源码是如何实现的。

1、Mutex

Mutex是个互斥锁,即MUTual EXclusion,对pthread的mutex进行了简单的封装,内部还有个嵌套类AutoLock,从名字上就可以看出这个类的功能是自动加锁解锁,使用原理正是基于变量的生命周期,对象创建时加锁,销毁时解锁。

Android中Mutex的源码路径为:

system/core/include/utils/Mutex.h

下面分析一下Mutex的源码实现。

// Mutex.h

// 宏定义惯例
#ifndef _LIBS_UTILS_MUTEX_H
#define _LIBS_UTILS_MUTEX_H

// C99引入的标准C库的头文件
// 定义了几种扩展的整数类型和宏
#include <stdint.h>

// 基本系统数据类型
#include <sys/types.h>

// 日期和时间相关函数
#include <time.h>

// 平台相关
// pthread即POSIX线程
// 定义了一系列线程及同步相关的接口
#if !defined(_WIN32)
# include <pthread.h>
#endif

// Android自定义了errno
#include <utils/Errors.h>

// Android自定义了时间格式转换函数
#include <utils/Timers.h>

// android名字空间
namespace android {

// Condition类前置声明
// 作为Mutex类的友元
class Condition;

/*
 * NOTE: This class is for code that builds on Win32.  Its usage is
 * deprecated for code which doesn't build for Win32.  New code which
 * doesn't build for Win32 should use std::mutex and std::lock_guard instead.
 *
 * Simple mutex class.  The implementation is system-dependent.
 *
 * The mutex must be unlocked by the thread that locked it.  They are not
 * recursive, i.e. the same thread can't lock it multiple times.
 */
class Mutex {
public:
    // PRIVATE限于同一进程内的多线程同步
    // SHARED支持进程间同步
    // 从下面的Mutex构造函数可以看出两者的区别
    enum {
        PRIVATE = 0,
        SHARED = 1
    };

	// 几个构造/析构函数
    Mutex();
    Mutex(const char* name);
    Mutex(int type, const char* name = NULL);
    ~Mutex();

	// 类似于pthread的lock/unlock/trylock
    status_t lock();
    void     unlock();
    status_t tryLock();

    // 平台相关
    // timedLock获取锁时限制了等待时间
#if defined(__ANDROID__)
    status_t timedLock(nsecs_t timeoutMilliseconds);
#endif

    // 自动加锁解锁
    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;
    };

private:
    // 友元声明
    friend class Condition;

    // 拷贝构造函数和赋值操作符私有声明而不定义
    // Mutex不能被拷贝
    Mutex(const Mutex&);
    Mutex& operator=(const Mutex&);

    // 平台相关
	// 非_WIN32时对pthread的mutex进行封装
#if !defined(_WIN32)
    pthread_mutex_t mMutex;
#else
    void  _init();
    void* mState;
#endif
};

// ---------------------------------------------------------------------------

#if !defined(_WIN32)

// 构造函数调用pthread_mutex_init初始化mutex
inline Mutex::Mutex() {
    pthread_mutex_init(&mMutex, NULL);
}

// 构造函数调用pthread_mutex_init初始化mutex
// __attribute__是GCC的一个特性
// unused表示其后的实参name没有被使用
inline Mutex::Mutex(__attribute__((unused)) const char* name) {
    pthread_mutex_init(&mMutex, NULL);
}

// 指定mutex类型的构造函数
// 当type为SHARED时
// 通过pthread_mutexattr_t设置其属性为PTHREAD_PROCESS_SHARED
// 表示mutex支持多进程
inline Mutex::Mutex(int type, __attribute__((unused)) const char* name) {
    if (type == SHARED) {
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_mutex_init(&mMutex, &attr);
        pthread_mutexattr_destroy(&attr);
    } else {
        pthread_mutex_init(&mMutex, NULL);
    }
}

// 析构函数调用pthread_mutex_destroy销毁mutex对象
inline Mutex::~Mutex() {
    pthread_mutex_destroy(&mMutex);
}

// lock加锁时调用了pthread_mutex_lock
// 锁被占用时会阻塞
// 成功时返回0
// 失败时返回一个errno
// 这些errno和status_t类型在utils/Errors.h中定义
inline status_t Mutex::lock() {
    return -pthread_mutex_lock(&mMutex);
}

// unlock解锁时调用了pthread_mutex_unlock
inline void Mutex::unlock() {
    pthread_mutex_unlock(&mMutex);
}

// trylock加锁时调用了pthread_mutex_trylock
// 锁被占用时会直接返回二不会等待
inline status_t Mutex::tryLock() {
    return -pthread_mutex_trylock(&mMutex);
}

// 特有的timedLock
// 加锁阻塞时限制了等待的时间
// nsecs_t在utils/Timers.h中定义
// timespec结构体的两个成员是秒和纳秒
#if defined(__ANDROID__)
inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
    const struct timespec ts = {
        /* .tv_sec = */ static_cast<time_t>(timeoutNs / 1000000000),
        /* .tv_nsec = */ static_cast<long>(timeoutNs % 1000000000),
    };
    return -pthread_mutex_timedlock(&mMutex, &ts);
}
#endif

#endif // !defined(_WIN32)

// ---------------------------------------------------------------------------

// AutoMutex惯用法:
// 在函数中需要加锁时先声明一个AutoMutex局部变量
// AutoMutex局部变量自动销毁时便会解锁
typedef Mutex::Autolock AutoMutex;

}; // namespace android

#endif // _LIBS_UTILS_MUTEX_H

2、Condition

Condition条件变量同样是对pthread的条件变量进行了封装,不过具体实现还使用了Mutex。当条件满足时直接返回,继续执行未完成的操作,否则就会等待,直到条件满足而被唤醒。

Android中Condition的源码路径为:

system/core/include/utils/Condition.h

下面分析一下Condition的源码实现。

// Condition.h

#ifndef _LIBS_UTILS_CONDITION_H
#define _LIBS_UTILS_CONDITION_H

#include <stdint.h>
#include <sys/types.h>
#include <time.h>

#if !defined(_WIN32)
# include <pthread.h>
#endif

#include <utils/Errors.h>
#include <utils/Mutex.h>
#include <utils/Timers.h>

namespace android {

// DO NOT USE: please use std::condition_variable instead.

/*
 * Condition variable class.  The implementation is system-dependent.
 *
 * Condition variables are paired up with mutexes.  Lock the mutex,
 * call wait(), then either re-wait() if things aren't quite what you want,
 * or unlock the mutex and continue.  All threads calling wait() must
 * use the same mutex for a given Condition.
 *
 * On Android and Apple platforms, these are implemented as a simple wrapper
 * around pthread condition variables.  Care must be taken to abide by
 * the pthreads semantics, in particular, a boolean predicate must
 * be re-evaluated after a wake-up, as spurious wake-ups may happen.
 */
// 条件变量实际上是对互斥锁的一种扩展
// 条件变量允许线程阻塞并等待其它的线程发信号将其唤醒
class Condition {
public:
	// PRIVATE和SHARED的含义同Mutex中的用法
    enum {
        PRIVATE = 0,
        SHARED = 1
    };

    // 唤醒等待者
    // 唤醒一个还是全部
    // 对应于signal和broadcast
    enum WakeUpType {
        WAKE_UP_ONE = 0,
        WAKE_UP_ALL = 1
    };

    Condition();
    Condition(int type);
    ~Condition();

    // 阻塞式等待条件变量或者设定延时等待时间
    status_t wait(Mutex& mutex);
    status_t waitRelative(Mutex& mutex, nsecs_t reltime);

    // 唤醒单个等待者或者所有等待者
    void signal();
    void signal(WakeUpType type) {
        if (type == WAKE_UP_ONE) {
            signal();
        } else {
            broadcast();
        }
    }
    void broadcast();

private:
// 封装了pthread_cond_t条件变量
#if !defined(_WIN32)
    pthread_cond_t mCond;
#else
    void* mState;
#endif
};

// ---------------------------------------------------------------------------

#if !defined(_WIN32)

// 构造函数调用pthread_cond_init初始化条件变量
inline Condition::Condition() {
    pthread_cond_init(&mCond, NULL);
}

// 原理同Mutex
// 当类型为SHARED时
// 通过pthread_condattr_t设置其属性为PTHREAD_PROCESS_SHARED
// 以支持进程间的同步
inline Condition::Condition(int type) {
    if (type == SHARED) {
        pthread_condattr_t attr;
        pthread_condattr_init(&attr);
        pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_cond_init(&mCond, &attr);
        pthread_condattr_destroy(&attr);
    } else {
        pthread_cond_init(&mCond, NULL);
    }
}

// 析构函数调用pthread_cond_destroy销毁条件变量
inline Condition::~Condition() {
    pthread_cond_destroy(&mCond);
}

// 调用pthread_cond_wait等待条件变量
// 这个wait机制比较有意思
// wait前首先要给mutex加锁
// wait内部会先给mutex解锁然后等待
// 直到条件满足时再给mutex加锁并返回
// 这些操作是一个原子操作
inline status_t Condition::wait(Mutex& mutex) {
    return -pthread_cond_wait(&mCond, &mutex.mMutex);
}

// timedWait设定了延时等待时间
inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
#if defined(HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE)
    struct timespec ts;
    ts.tv_sec  = reltime / 1000000000;
    ts.tv_nsec = reltime % 1000000000;
    return -pthread_cond_timedwait_relative_np(&mCond, &mutex.mMutex, &ts);
#else // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
    struct timespec ts;
#if defined(__linux__)
    clock_gettime(CLOCK_REALTIME, &ts);
#else // __APPLE__
    struct timeval t;
    gettimeofday(&t, NULL);
    ts.tv_sec = t.tv_sec;
    ts.tv_nsec= t.tv_usec * 1000;
#endif
    ts.tv_sec  += reltime / 1000000000;
    ts.tv_nsec += reltime % 1000000000;
    if (ts.tv_nsec >= 1000000000) {
        ts.tv_nsec -= 1000000000;
        ts.tv_sec  += 1;
    }
    return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
#endif // HAVE_PTHREAD_COND_TIMEDWAIT_RELATIVE
}

// 调用pthread_cond_signal唤醒某个等待者
inline void Condition::signal() {
    pthread_cond_signal(&mCond);
}

// 调用pthread_cond_broadcast唤醒所有等待者
inline void Condition::broadcast() {
    pthread_cond_broadcast(&mCond);
}

#endif // !defined(_WIN32)

}; // namespace android

#endif // _LIBS_UTILS_CONDITON_H

3、RWLock

RWLock即读写锁,同样是对pthread的rwlock进行了封装,基本原理是可以多个线程占用读锁,但是只能一个线程占用写锁。

Android中RWLock的源码路径为:

system/core/include/utils/RWLock.h

下面分析一下RWLock的源码实现,代码结构与Mutex的很相似。

// RWLock.h

#ifndef _LIBS_UTILS_RWLOCK_H
#define _LIBS_UTILS_RWLOCK_H

#include <stdint.h>
#include <sys/types.h>

#if !defined(_WIN32)
# include <pthread.h>
#endif

#include <utils/Errors.h>

// 定义了线程相关的数据类型和优先级
#include <utils/ThreadDefs.h>

namespace android {

#if !defined(_WIN32)

/*
 * Simple mutex class.  The implementation is system-dependent.
 *
 * The mutex must be unlocked by the thread that locked it.  They are not
 * recursive, i.e. the same thread can't lock it multiple times.
 */
// RWLock读写锁的特点是:
// 当读写锁处于写模式时
// 其后的读锁/写锁都会阻塞
// 当读写锁处于读模式时
// 其后的读锁仍可以获得控制权
// 但写锁将被阻塞以及这个写锁之后的读锁也会被阻塞
class RWLock {
public:
    // 同样用法的enum
    enum {
        PRIVATE = 0,
        SHARED = 1
    };

    // 类似于Mutex的构造/析构函数
    RWLock();
    RWLock(const char* name);
    RWLock(int type, const char* name = NULL);
    ~RWLock();

    // 几个读锁/写锁及解锁函数
    status_t readLock();
    status_t tryReadLock();
    status_t writeLock();
    status_t tryWriteLock();
    void     unlock();

    // 类似于Mutex的自动读锁
    class AutoRLock {
    public:
        inline AutoRLock(RWLock& rwlock) : mLock(rwlock)  { mLock.readLock(); }
        inline ~AutoRLock() { mLock.unlock(); }
    private:
        RWLock& mLock;
    };

    // 类似于Mutex的自动写锁
    class AutoWLock {
    public:
        inline AutoWLock(RWLock& rwlock) : mLock(rwlock)  { mLock.writeLock(); }
        inline ~AutoWLock() { mLock.unlock(); }
    private:
        RWLock& mLock;
    };

private:
    // 类似于Mutex的用法
    // 禁止RWLock拷贝
            RWLock(const RWLock&);
    RWLock& operator=(const RWLock&);

    // 对pthread_rwlock_t进行了封装
    pthread_rwlock_t mRWLock;
};

// 构造函数调用pthread_rwlock_init对读写锁进行初始化
inline RWLock::RWLock() {
    pthread_rwlock_init(&mRWLock, NULL);
}

// 构造函数调用pthread_rwlock_init对读写锁进行初始化
// unused的name没有实际用处
// 猜想大概是个备用参数
inline RWLock::RWLock(__attribute__((unused)) const char* name) {
    pthread_rwlock_init(&mRWLock, NULL);
}

// 当type为SHARED时
// 通过对应的pthread_rwlockattr_t设置其属性为PTHREAD_PROCESS_SHARED
// 以支持跨进程的同步
inline RWLock::RWLock(int type, __attribute__((unused)) const char* name) {
    if (type == SHARED) {
        pthread_rwlockattr_t attr;
        pthread_rwlockattr_init(&attr);
        pthread_rwlockattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
        pthread_rwlock_init(&mRWLock, &attr);
        pthread_rwlockattr_destroy(&attr);
    } else {
        pthread_rwlock_init(&mRWLock, NULL);
    }
}

// 析构函数调用pthread_rwlock_destroy销毁读写锁
inline RWLock::~RWLock() {
    pthread_rwlock_destroy(&mRWLock);
}

// 调用pthread_rwlock_rdlock以获取读锁
inline status_t RWLock::readLock() {
    return -pthread_rwlock_rdlock(&mRWLock);
}

// 调用pthread_rwlock_tryrdlock以获取读锁并不会阻塞
inline status_t RWLock::tryReadLock() {
    return -pthread_rwlock_tryrdlock(&mRWLock);
}

// 调用pthread_rwlock_wrlock以获取写锁
inline status_t RWLock::writeLock() {
    return -pthread_rwlock_wrlock(&mRWLock);
}

// 调用pthread_rwlock_trywrlock以获取写锁并不会阻塞
inline status_t RWLock::tryWriteLock() {
    return -pthread_rwlock_trywrlock(&mRWLock);
}

// 调用pthread_rwlock_unlock以解锁
inline void RWLock::unlock() {
    pthread_rwlock_unlock(&mRWLock);
}

#endif // !defined(_WIN32)

// ---------------------------------------------------------------------------
}; // namespace android
// ---------------------------------------------------------------------------

#endif // _LIBS_UTILS_RWLOCK_H

4、Barrier

Barrier是基于Mutex和Condition实现的一个模型,专门为SurfaceFlinger设计,用起来更加简单,而不是像Mutex和Condition那样作为一个通用的Utility。

Android中Barrier的源码路径为:

framework/native/services/surfaceflinger/Barrier.h

下面分析一下Barrier 的源码实现。

// Barrier.h

#ifndef ANDROID_BARRIER_H
#define ANDROID_BARRIER_H

#include <stdint.h>
#include <sys/types.h>
#include <utils/threads.h>

namespace android {

// Barrier集合了Mutex和Condition
// 所谓的条件变量通过enum值OPENED和CLOSED实现
// 提供了3个函数open/close/wait
// 这3个函数都对state进行了读/写
// 所以需要加锁保护
// 否则会造成死锁等意想不到的现象
class Barrier
{
public:
    // 初始状态为CLOSED
    inline Barrier() : state(CLOSED) { }
    inline ~Barrier() { }

    // open函数设置state为OPENED
    // 调用broadcast函数解除wait函数的阻塞状态
    void open() {
        Mutex::Autolock _l(lock);
        state = OPENED;
        cv.broadcast();
    }

    // close函数重置state为CLOSED
    // 这时将阻塞wait函数
    void close() {
        Mutex::Autolock _l(lock);
        state = CLOSED;
    }

    // 当state为OPEND时
    // wait被唤醒
    // 从而退出wait
    void wait() const {
        Mutex::Autolock _l(lock);
        while (state == CLOSED) {
            cv.wait(lock);
        }
    }
private:
    enum { OPENED, CLOSED };
    mutable  Mutex     lock;
    mutable  Condition cv;
    volatile int       state;
};

}; // namespace android

#endif // ANDROID_BARRIER_H

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值