class OSMutex
{
public:
OSMutex();
~OSMutex();
inline void Lock();
inline void Unlock();
// Returns true on successful grab of the lock, false on failure
inline Bool16 TryLock();
private:
#ifdef __Win32__
CRITICAL_SECTION fMutex;
DWORD fHolder;
UInt32 fHolderCount;
#elif !__PTHREADS_MUTEXES__
mymutex_t fMutex;
#else
pthread_mutex_t fMutex;
// These two platforms don't implement pthreads recursive mutexes, so
// we have to do it manually
pthread_t fHolder;
UInt32 fHolderCount;
#endif
#if __PTHREADS_MUTEXES__ || __Win32__
void RecursiveLock();
void RecursiveUnlock();
Bool16 RecursiveTryLock();
#endif
friend class OSCond;
};
class OSMutexLocker
{
public:
OSMutexLocker(OSMutex* inMutexP) : fMutex(inMutexP) { if (fMutex != NULL) fMutex->Lock(); }
~OSMutexLocker() { if (fMutex != NULL) fMutex->Unlock(); }
void Lock() { if (fMutex != NULL) fMutex->Lock(); }
void Unlock() { if (fMutex != NULL) fMutex->Unlock(); }
private:
OSMutex* fMutex;
};
OSMutexLocker 通过构造函数和析构函数完成对区块的上锁和解锁,当需要对部分进行锁定时:
fun()
{
operation........
{
OSMutexLocker locker(...)
}
opearation.....
}