一个简单但很好用的线程锁

来源:互联网 发布:网络变压器引脚定义 编辑:程序博客网 时间:2024/05/16 13:06

#ifndef __LOCK_H__
#define __LOCK_H__

#ifdef _WIN32
#include <WinSock2.h>
#else
#include <pthread.h>
#endif

class CLock
{
public:
 class CMutex
 {
  friend class CLock;
 public:
  CMutex()
  {
#ifdef _WIN32
   InitializeCriticalSection(&m_cs);
#else
   pthread_mutex_init(&m_tmt, NULL);
#endif
  }
  
  ~CMutex()
  {
#ifdef _WIN32
   DeleteCriticalSection(&m_cs);
#else
   pthread_mutex_destroy(&m_tmt);
#endif
  }
  
 private:
  void lock()
  {
#ifdef _WIN32
   EnterCriticalSection(&m_cs);
#else
   pthread_mutex_lock(&m_tmt);
#endif
  }
  
  void unlock()
  {
#ifdef _WIN32
   LeaveCriticalSection(&m_cs);
#else
   pthread_mutex_unlock(&m_tmt);
#endif
  }
  
 private:
#ifdef _WIN32
  CRITICAL_SECTION m_cs;
#else
  pthread_mutex_t  m_tmt;
#endif
 };
 
 explicit CLock(CMutex& mutex) : m_mutex(mutex) {m_mutex.lock();}
 ~CLock() {m_mutex.unlock();}
 
 private:
  CMutex&    m_mutex;
};

#endif //__LOCK_H__