一些适用于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:他们只是简单的小工具类,他们只是保证了“能用”,当中可能有很多不足,或者不适用特别的情况。