簡單的多線程同步的小工具類
一些適用于Windows下的多線程同步的小工具類。快速互斥鎖,封裝了臨界區的Windows API:
class FastMutex

{
private:
CRITICAL_SECTION m_Cs;
public:
FastMutex()
{ ::InitializeCriticalSection(&this->m_Cs); }
~FastMutex()
{ ::DeleteCriticalSection(&this->m_Cs); }
void Lock()
{ ::EnterCriticalSection(&this->m_Cs); }
bool TryLock()
{ return ::TryEnterCriticalSection(&this->m_Cs) ? true : false; }
void Unlock()
{ ::LeaveCriticalSection(&this->m_Cs); }
};簡單封裝了Windows的信號量(Semaphore)的API。
class FastSemaphore

{
private:
HANDLE m_hSemaphore;
long m_lMaximumCount;
public:
FastSemaphore(long lMaximumCount)
{
this->m_hSemaphore = ::CreateSemaphore(NULL, lMaximumCount, lMaximumCount, NULL);
if (this->m_hSemaphore == NULL) throw "Call to CreateSemaphore() failed. Could not create semaphore.";
this->m_lMaximumCount = lMaximumCount;
};

~FastSemaphore()
{ ::CloseHandle(this->m_hSemaphore); };

long GetMaximumCount() const
{ return this->m_lMaximumCount; };
void Inc()
{ ::WaitForSingleObject(this->m_hSemaphore, INFINITE); };
void Dec()
{ ::ReleaseSemaphore(this->m_hSemaphore, 1, NULL); };
void Dec(long lCount)
{ ::ReleaseSemaphore(this->m_hSemaphore, lCount, NULL); };
};讀寫互斥鎖,多線程可以同時讀取同一個文件,但是卻不能同時寫入同一個文件,對某一個文件的寫操作必須是某一個線程所獨占的。
class ReadWriteMutex

{
private:
FastMutex m_qMutex;
FastSemaphore m_qSemaphore;
public:
ReadWriteMutex(long lMaximumReaders): m_qSemaphore(lMaximumReaders)
{};

void lockRead()
{ m_qSemaphore.Inc(); };
void unlockRead()
{ m_qSemaphore.Dec(); };
void lockWrite()
{
m_qMutex.Lock();
for (int i = 0; i < maxReaders(); ++i) m_qSemaphore.Inc();
m_qMutex.Unlock();
};

void unlockWrite()
{ m_qSemaphore.Dec(m_qSemaphore.GetMaximumCount()); };
int maxReaders() const
{ return m_qSemaphore.GetMaximumCount(); };
};區域鎖
template <class M>
class ScopedLock

{
public:
inline ScopedLock(M& mutex): _mutex(mutex)
{
_mutex.Lock();
}
inline ~ScopedLock()
{
_mutex.Unlock();
}
private:
M& _mutex;
ScopedLock();
ScopedLock(const ScopedLock&);
ScopedLock& operator = (const ScopedLock&);
};
void xxxFuc()

{
ScopeLock<FastMutex> mutex;

}區域解鎖
template <class M>
class ScopedUnlock

{
public:
inline ScopedUnlock(M& mutex, bool unlockNow = true): _mutex(mutex)
{
if (unlockNow)
_mutex.Unlock();
}
inline ~ScopedUnlock()
{
_mutex.Lock();
}
private:
M& _mutex;
ScopedUnlock();
ScopedUnlock(const ScopedUnlock&);
ScopedUnlock& operator = (const ScopedUnlock&);
};
NOTE:他們只是簡單的小工具類,他們只是保證了“能用”,當中可能有很多不足,或者不適用特別的情況。

