在做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文件

  Code

  #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

  ......................