在Android中,封裝的同步類主要有Mutex(AutoMutex)
與Condition
。
這兩個類在android中被大量的使用,這也說明這兩個類是非常重要的。
一、Mutex(AutoMutex)與Condition代碼分析
1.1 Mutex(AutoMutex)代碼分析
Mutex是互斥類,用于多線程訪問同一個資源的時候,保證一次只有一個線程能訪問該資源。
system/core/include/utils/Mutex.h
#ifndef _LIBS_UTILS_MUTEX_H
#define _LIBS_UTILS_MUTEX_H
#include <stdint.h>
#include <sys/types.h>
#include <time.h>
#if !defined(_WIN32)
# include <pthread.h>
#endif
#include <utils/Errors.h>
#include <utils/Timers.h>
// Enable thread safety attributes only with clang.
// The attributes can be safely erased when compiling with other compilers.
#if defined(__clang__) && (!defined(SWIG))
#define THREAD_ANNOTATION_ATTRIBUTE__(x) __attribute__((x))
#else
#define THREAD_ANNOTATION_ATTRIBUTE__(x) // no-op
#endif
#define CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(capability(x))
#define SCOPED_CAPABILITY THREAD_ANNOTATION_ATTRIBUTE__(scoped_lockable)
#define GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(guarded_by(x))
#define PT_GUARDED_BY(x) THREAD_ANNOTATION_ATTRIBUTE__(pt_guarded_by(x))
#define ACQUIRED_BEFORE(...) THREAD_ANNOTATION_ATTRIBUTE__(acquired_before(__VA_ARGS__))
#define ACQUIRED_AFTER(...) THREAD_ANNOTATION_ATTRIBUTE__(acquired_after(__VA_ARGS__))
#define REQUIRES(...) THREAD_ANNOTATION_ATTRIBUTE__(requires_capability(__VA_ARGS__))
#define REQUIRES_SHARED(...) THREAD_ANNOTATION_ATTRIBUTE__(requires_shared_capability(__VA_ARGS__))
#define ACQUIRE(...) THREAD_ANNOTATION_ATTRIBUTE__(acquire_capability(__VA_ARGS__))
#define ACQUIRE_SHARED(...) THREAD_ANNOTATION_ATTRIBUTE__(acquire_shared_capability(__VA_ARGS__))
#define RELEASE(...) THREAD_ANNOTATION_ATTRIBUTE__(release_capability(__VA_ARGS__))
#define RELEASE_SHARED(...) THREAD_ANNOTATION_ATTRIBUTE__(release_shared_capability(__VA_ARGS__))
#define TRY_ACQUIRE(...) THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_capability(__VA_ARGS__))
#define TRY_ACQUIRE_SHARED(...) \
THREAD_ANNOTATION_ATTRIBUTE__(try_acquire_shared_capability(__VA_ARGS__))
#define EXCLUDES(...) THREAD_ANNOTATION_ATTRIBUTE__(locks_excluded(__VA_ARGS__))
#define ASSERT_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_capability(x))
#define ASSERT_SHARED_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(assert_shared_capability(x))
#define RETURN_CAPABILITY(x) THREAD_ANNOTATION_ATTRIBUTE__(lock_returned(x))
#define NO_THREAD_SAFETY_ANALYSIS THREAD_ANNOTATION_ATTRIBUTE__(no_thread_safety_analysis)
// ---------------------------------------------------------------------------
namespace android {
// ---------------------------------------------------------------------------
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 CAPABILITY("mutex") Mutex {
public:
//兩種類型:PRIVATE是進程內部使用的;SHARED是適用于跨進程共享的。
//如不指定,缺省是PRIVATE的類型。
enum {
PRIVATE = 0,
SHARED = 1
};
Mutex();//構造函數
explicit Mutex(const char* name);//構造函數
explicit Mutex(int type, const char* name = nullptr);//構造函數,type就是上面的那兩種類型
~Mutex();//析構函數
// lock or unlock the mutex
status_t lock() ACQUIRE();//獲取鎖。如果獲取就返回,否則掛起等待
void unlock() RELEASE();//釋放鎖
// lock if possible; returns 0 on success, error otherwise
//如果當前鎖可被獲取(未被別的線程獲取)就lock,否則就直接返回。
//返回值:0代表成功;其它值失敗。
//與lock()的區別在于不論成功與否都會及時返回,而不是掛起等待。
status_t tryLock() TRY_ACQUIRE(0);
#if defined(__ANDROID__)
// Lock the mutex, but don't wait longer than timeoutNs (relative time).
// Returns 0 on success, TIMED_OUT for failure due to timeout expiration.
//
// OSX doesn't have pthread_mutex_timedlock() or equivalent. To keep
// capabilities consistent across host OSes, this method is only available
// when building Android binaries.
//
// FIXME?: pthread_mutex_timedlock is based on CLOCK_REALTIME,
// which is subject to NTP adjustments, and includes time during suspend,
// so a timeout may occur even though no processes could run.
// Not holding a partial wakelock may lead to a system suspend.
status_t timedLock(nsecs_t timeoutNs) TRY_ACQUIRE(0);
#endif
// Manages the mutex automatically. It'll be locked when Autolock is
// constructed and released when Autolock goes out of scope.
//Autolock是為了簡化Mutex的使用而定義的,并且充分利用了c++的構造與析構機制
//可以看出,在構造函數中mLock.lock()加鎖,在析構函數中mLock.unlock() 解鎖。
//所以,對一個需要加鎖的函數來說,我們只需要在函數開始處,聲明這樣 (Mutex::Autolock autolock(mLock);),一個變量,它就會加鎖,
//等函數退出時,這樣一個臨時變量就會析構,就會解鎖。
//android系統里幾乎到處都是這種使用,或者AutoMutex _l(mLock)這種使用
//這兩種使用是一樣的效果的,因為下面有這樣一行代碼typedefMutex::Autolock AutoMutex;
//這種設計師非常優秀的,如果你手動去lock,unlock,就有可能忘了unlock,這樣的會很容易死鎖,死鎖在android系統里后果是非常嚴重,大多數情況都會系統重啟
//大家都知道C++的構造函數析構函數是成對出現的,用了構造函數中mLock.lock()加鎖,
//在析構函數中mLock.unlock()解鎖這種設計之后,就不會出現忘了unlock的情況了
class SCOPED_CAPABILITY Autolock {
public:
//其實這里不加inline也是沒有關系的,在C++里編譯器會自動去檢查這個函數體
//如果函數體邏輯足夠簡單,會自動把他當成inline函數,為了養成良好的代碼習慣,還是要加上
inline explicit Autolock(Mutex& mutex) ACQUIRE(mutex) : mLock(mutex) { mLock.lock(); }
inline explicit Autolock(Mutex* mutex) ACQUIRE(mutex) : mLock(*mutex) { mLock.lock(); }
inline ~Autolock() RELEASE() { mLock.unlock(); }
private:
Mutex& mLock;
// Cannot be copied or moved - declarations only
Autolock(const Autolock&);
Autolock& operator=(const Autolock&);
};
private:
friend class Condition;//友元類Condition
// A mutex cannot be copied
Mutex(const Mutex&);
Mutex& operator=(const Mutex&);
#if !defined(_WIN32)
pthread_mutex_t mMutex;
#else
void _init();
void* mState;
#endif
};
// ---------------------------------------------------------------------------
#if !defined(_WIN32)
inline Mutex::Mutex() {
pthread_mutex_init(&mMutex, nullptr);
}
inline Mutex::Mutex(__attribute__((unused)) const char* name) {
pthread_mutex_init(&mMutex, nullptr);
}
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, nullptr);
}
}
inline Mutex::~Mutex() {
pthread_mutex_destroy(&mMutex);
}
inline status_t Mutex::lock() {
return -pthread_mutex_lock(&mMutex);
}
inline void Mutex::unlock() {
pthread_mutex_unlock(&mMutex);
}
inline status_t Mutex::tryLock() {
return -pthread_mutex_trylock(&mMutex);
}
#if defined(__ANDROID__)
inline status_t Mutex::timedLock(nsecs_t timeoutNs) {
timeoutNs += systemTime(SYSTEM_TIME_REALTIME);
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)
// ---------------------------------------------------------------------------
/*
* 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;
// ---------------------------------------------------------------------------
} // namespace android
// ---------------------------------------------------------------------------
#endif // _LIBS_UTILS_MUTEX_H
1.2 Condition代碼分析
Condition
條件類,在多線程同步中,主要是下面這種使用場景使用到condition
。
線程A做初始化工作,而其他線程,比如線程B、C必須等到A初始化工作完后才能工作,即線程B、C在等待一個條件,我們稱B、C為等待者。
當線程A完成初始化工作時,會觸發這個條件,那么等待者B、C就會被喚醒。觸發這個條件的A就是觸發者。
上面的使用場景非常形象,而且條件類提供的函數也非常形象,它的代碼如下所示:
system/core/include/utils/Condition.h
#ifndef _LIBS_UTILS_CONDITION_H
#define _LIBS_UTILS_CONDITION_H
#include <limits.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是適用于跨進程共享的。
//如不指定,缺省是PRIVATE的類型。
enum {
PRIVATE = 0,
SHARED = 1
};
enum WakeUpType {
WAKE_UP_ONE = 0,
WAKE_UP_ALL = 1
};
Condition();// 構造函數
explicit Condition(int type);//構造函數,type就是上面的那兩種類型
~Condition();//析構函數
// Wait on the condition variable. Lock the mutex before calling.
// Note that spurious wake-ups may happen.
//線程B和C等待事件,wait這個名字也很形象
status_t wait(Mutex& mutex);
// same with relative timeout
//線程B和C的超時等待,B和C可以指定等待時間,當超過這個時間,條件卻還不滿足,則退出等待。
status_t waitRelative(Mutex& mutex, nsecs_t reltime);
// Signal the condition variable, allowing one thread to continue.
//觸發者A用來通知條件已經滿足,但是B和C只有一個會被喚醒
void signal();
// Signal the condition variable, allowing one or all threads to continue.
void signal(WakeUpType type) {
if (type == WAKE_UP_ONE) {
signal();
} else {
broadcast();
}
}
// Signal the condition variable, allowing all threads to continue.
//觸發者A用來通知條件已經滿足,所有等待者都會被喚醒。
void broadcast();
private:
#if !defined(_WIN32)
pthread_cond_t mCond;
#else
void* mState;
#endif
};
// ---------------------------------------------------------------------------
#if !defined(_WIN32)
inline Condition::Condition() : Condition(PRIVATE) {
}
inline Condition::Condition(int type) {
pthread_condattr_t attr;
pthread_condattr_init(&attr);
#if defined(__linux__)
pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
#endif
if (type == SHARED) {
pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
}
pthread_cond_init(&mCond, &attr);
pthread_condattr_destroy(&attr);
}
inline Condition::~Condition() {
pthread_cond_destroy(&mCond);
}
inline status_t Condition::wait(Mutex& mutex) {
return -pthread_cond_wait(&mCond, &mutex.mMutex);
}
inline status_t Condition::waitRelative(Mutex& mutex, nsecs_t reltime) {
struct timespec ts;
#if defined(__linux__)
clock_gettime(CLOCK_MONOTONIC, &ts);
#else // __APPLE__
// Apple doesn't support POSIX clocks.
struct timeval t;
gettimeofday(&t, nullptr);
ts.tv_sec = t.tv_sec;
ts.tv_nsec = t.tv_usec*1000;
#endif
// On 32-bit devices, tv_sec is 32-bit, but `reltime` is 64-bit.
int64_t reltime_sec = reltime/1000000000;
ts.tv_nsec += static_cast<long>(reltime%1000000000);
if (reltime_sec < INT64_MAX && ts.tv_nsec >= 1000000000) {
ts.tv_nsec -= 1000000000;
++reltime_sec;
}
int64_t time_sec = ts.tv_sec;
if (time_sec > INT64_MAX - reltime_sec) {
time_sec = INT64_MAX;
} else {
time_sec += reltime_sec;
}
ts.tv_sec = (time_sec > LONG_MAX) ? LONG_MAX : static_cast<long>(time_sec);
return -pthread_cond_timedwait(&mCond, &mutex.mMutex, &ts);
}
//inline函數
//signal()和broadcast()的實現是憑借調用了Raw API的pthread_cond_signal(&mCond)與pthread_cond_broadcast(&mCond)
//這里要重點說明的是,Condition類必須配合Mutex來使用。
// 在上面的代碼中,不論是wait、waitRelative、signal還是broadcast的調用,都放在一個Mutex的lock和unlock范圍中,尤其是wait和waitRelative函數的調用,這是強制性的。
inline void Condition::signal() {
pthread_cond_signal(&mCond);
}
inline void Condition::broadcast() {
pthread_cond_broadcast(&mCond);
}
#endif // !defined(_WIN32)
// ---------------------------------------------------------------------------
} // namespace android
// ---------------------------------------------------------------------------
#endif // _LIBS_UTILS_CONDITON_H
二、為什么android要封裝AutoMutex
在android系統中,死鎖是非常嚴重的,基本都是會引起系統死機,crash,重啟的,并且死鎖在android系統開發中,也是會經常碰見的。所以我們要盡量避免死鎖,android就給我們封裝了AutoMutex。它充分利用了c++的構造與析構機制,在構造函數中mLock.lock()
加鎖,在析構函數中mLock.unlock()
解鎖。
對一個需要加鎖的函數來說,我們只需要在函數開始處,AutoMutex _l(mLock)
就完成了加鎖,等函數退出時,這樣一個臨時變量就會析構,就會解鎖。
三、Autolock/AutoMutex與Condition的使用
3.1 Autolock/AutoMutex的使用
用法比較簡單,定義一個局部臨時的AutoMutex
變量,在該變量定義的地方,構造函數被自動調用,會執行Mutex的lock()
操作;在該變量作用域結束的地方,析構函數會被自動調用,會執行Mutex
的unlock
操作。
所以,你只需要在Mutex
保護的區域開始的地方定義一個AutoMutex
變量即可,即可實現用Mutex
對該區域的保護。
3.2 Condition的使用
我們看一個android原生的類是怎么使用condition和Mutex的。
這個例子是Thread類的requestExitAndWait,目的是等待工作線程退出,代碼如下所示:
system/core/libutils/Threads.cpp
status_t Thread::requestExitAndWait()
{
Mutex::Autolock _l(mLock);
if (mThread == getThreadId()) {
ALOGW(
"Thread (this=%p): don't call waitForExit() from this "
"Thread object's thread. It's a guaranteed deadlock!",
this);
return WOULD_BLOCK;
}
mExitPending = true;
while (mRunning == true) {
mThreadExitedCondition.wait(mLock);//這里wait
}
// This next line is probably not needed any more, but is being left for
// historical reference. Note that each interested party will clear flag.
mExitPending = false;
return mStatus;
}
那么,什么時候會觸發這個條件呢?是在工作線程退出前。其代碼如下所示:
int Thread::_threadLoop(void* user)
{
Thread* const self = static_cast<Thread*>(user);
sp<Thread> strong(self->mHoldSelf);
wp<Thread> weak(strong);
self->mHoldSelf.clear();
#if defined(__ANDROID__)
// this is very useful for debugging with gdb
self->mTid = gettid();
#endif
bool first = true;
do {
bool result;
if (first) {
first = false;
self->mStatus = self->readyToRun();
result = (self->mStatus == OK);
if (result && !self->exitPending()) {
// Binder threads (and maybe others) rely on threadLoop
// running at least once after a successful ::readyToRun()
// (unless, of course, the thread has already been asked to exit
// at that point).
// This is because threads are essentially used like this:
// (new ThreadSubclass())->run();
// The caller therefore does not retain a strong reference to
// the thread and the thread would simply disappear after the
// successful ::readyToRun() call instead of entering the
// threadLoop at least once.
result = self->threadLoop();
}
} else {
result = self->threadLoop();
}
// establish a scope for mLock
{
Mutex::Autolock _l(self->mLock);
if (result == false || self->mExitPending) {
self->mExitPending = true;
self->mRunning = false;
// clear thread ID so that requestExitAndWait() does not exit if
// called by a new thread using the same thread ID as this one.
self->mThread = thread_id_t(-1);
// note that interested observers blocked in requestExitAndWait are
// awoken by broadcast, but blocked on mLock until break exits scope
self->mThreadExitedCondition.broadcast(); //這里broadcast
break;
}
}
// Release our strong reference, to let a chance to the thread
// to die a peaceful death.
strong.clear();
// And immediately, re-acquire a strong reference for the next loop
strong = weak.promote();
} while(strong != nullptr);
return 0;
}
通過以上的學習,我們對Autolock/AutoMutex
與Condition
就有個深入的理解,
在以后android系統看到它們就知道他們的作用,已經怎么樣去使用它了,達到寫的代碼更少的bug。