在做C++的項目中發現,由於用慣了c#的lock(){}和java的Synchronize(){},windows自帶的臨界區,互斥量,內核事件,信號量用起來不太習慣,於是打算自己在vc++中封裝一個類似的東東。封裝這個我決定采用一個臨界區來做,最終的形式如下:
synchronize(object)
{
//....無論此處是否發生異常,object都能被釋放掉。和c#的lock一樣。
}
不多說,開始代碼。先定義一個Mutex類
class Mutex
{
public:
Mutex(void);
~Mutex(void);
void Lock();
void UnLock();
private:
CRITICAL_SECTION m_criticalSection;
};
實現如下
Mutex.cpp文件
#include "Mutex.h"
Mutex::Mutex(void)
{
InitializeCriticalSection(&m_criticalSection);
}
Mutex::~Mutex(void)
{
DeleteCriticalSection(&m_criticalSection);//保證對象被析構時候能夠刪除臨界區
}
void Mutex::Lock()
{
EnterCriticalSection(&m_criticalSection);
}
void Mutex::UnLock()
{
LeaveCriticalSection(&m_criticalSection);
}
在寫一個Lock類來包裝
頭文件文件
//為了方便把頭文件定義到了Mutex.h文件裡面去了,修改Mutex.h如、//下:
#define synchronized(M) for(Lock M##_lock = M; M##_lock; M##_lock.SetUnlock())//這句話後面會用到
class Mutex
{
public:
Mutex(void);
~Mutex(void);
void Lock();
void UnLock();
private:
CRITICAL_SECTION m_criticalSection;
};
class Lock
{
public:
Lock(Mutex &mutex);
~Lock(void);
void SetUnlock();
operator bool () const;
private:
Mutex &m_mutex;
bool m_locked;
};
Lock類的實現:Lock.cpp文件
#include "Mutex.h"
Lock::Lock(Mutex &mutex): m_mutex(mutex), m_locked(true)
{
m_mutex.Lock();
}
Lock::~Lock(void)
{/*一定要在析構函數中解鎖,因為不管發生什麼,只要對象離開他的生命周期(即離開大括號),都會調用其析構函數*/
m_mutex.UnLock();
}
void Lock::SetUnlock()
{
m_locked = false;
}
Lock::operator bool() const
{
return m_locked;
}
到這裡算是基板上告一段落了,你可以這麼用。
Mutex _mutex;
{
Lock lock(_mutex);
//...在這裡同步
}
但還差一點點,我要的目標是synchronize(){.....}
簡單!!!注意Mutex.h文件裡面的宏,沒錯!就他了!!!
#define synchronized(M) for(Lock M##_lock = M; M##_lock; M##_lock.SetUnlock())
大功告成!!!
來測試下
實際測試
#include "Mutex.h"
Mutex mutex1;//我的互斥量
into thread_count = 0;
DWORD CALLBACK thread_proc(LPVOID params)
{
for(int i = 0; i < 10; ++i)
{
synchronized(mutex1)//這裡同步!
{
for(char c = 'A'; c <= 'Z'; ++c)
{
printf("%c",c);
Sleep(2);
}
printf("\n");
}
}
thread_count--;
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
thread_count = 4;
CreateThread(0, 0, thread_proc, 0, 0, 0);
CreateThread(0, 0, thread_proc, 0, 0, 0);
CreateThread(0, 0, thread_proc, 0, 0, 0);
CreateThread(0, 0, thread_proc, 0, 0, 0);
while (thread_count)
Sleep(0);
getchar();
DeleteCriticalSection(&g_cs);
return 0;
}
輸出:
ABCD...........Z
ABCD............Z
ABCD...........Z
ABCD............Z
ABCD...........Z
ABCD............Z
......................
完美同步!