class Mutex
{
public:
Mutex(void);
~Mutex(void);
void Lock();
void UnLock();
private:
CRITICAL_SECTION m_criticalSection;
};
#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类的实现:

#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
......................