00001
00002
00003
00004 #ifndef SYNC_CTRL_H_BY_DAVID_MAISONAVE_HEADER_GUARD_
00005 #define SYNC_CTRL_H_BY_DAVID_MAISONAVE_HEADER_GUARD_
00006
00012 class sync_ctrl
00013 {
00014 public:
00015 virtual void lock()=0;
00016 virtual void unlock()=0;
00017 virtual bool trylock()=0;
00018 virtual ~sync_ctrl(){}
00019 };
00020
00021 #ifdef _WIN32
00022 class sync_ctrl_mutex : public sync_ctrl
00023 {
00024 public:
00025 sync_ctrl_mutex(LPCTSTR lpName = NULL, LPSECURITY_ATTRIBUTES lpMutexAttributes = NULL):m_hndl(CreateMutex(lpMutexAttributes, FALSE, lpName)){}
00026 ~sync_ctrl_mutex()
00027 {
00028 ReleaseMutex(m_hndl);
00029 CloseHandle(m_hndl);
00030 }
00031 void lock(){WaitForSingleObject(m_hndl, INFINITE);}
00032 void unlock(){ReleaseMutex(m_hndl);}
00033 bool trylock()
00034 {
00035 DWORD GoodLock = WaitForSingleObject(m_hndl, 1);
00036 return (GoodLock == WAIT_OBJECT_0);
00037 }
00038 private:
00039 HANDLE m_hndl;
00040 };
00041
00042 #if(_WIN32_WINNT >= 0x0400)
00043 class sync_ctrl_win32_critical : public sync_ctrl
00044 {
00045 public:
00046 sync_ctrl_win32_critical(){InitializeCriticalSection(&m_cs);}
00047 ~sync_ctrl_win32_critical(){DeleteCriticalSection(&m_cs);}
00048 void lock(){EnterCriticalSection(&m_cs);}
00049 void unlock(){LeaveCriticalSection(&m_cs);}
00050 bool trylock()
00051 {
00052
00053 BOOL GoodLock = TryEnterCriticalSection(&m_cs);
00054 return (GoodLock == TRUE);
00055 }
00056 private:
00057 CRITICAL_SECTION m_cs;
00058 };
00059 typedef sync_ctrl_win32_critical sync_ctrl_default;
00060 #else
00061 typedef sync_ctrl_mutex sync_ctrl_default;
00062 #endif
00063
00064 #else //_WIN32
00065
00066
00067
00068 class sync_ctrl_posix_mutex : public sync_ctrl
00069 {
00070 public:
00071 sync_ctrl_posix_mutex():m_mutex(PTHREAD_MUTEX_INITIALIZER){}
00072 ~sync_ctrl_posix_mutex(){pthread_mutex_destroy(&m_mutex);}
00073 void lock(){pthread_mutex_lock(&m_mutex);}
00074 void unlock(){pthread_mutex_unlock(&m_mutex);}
00075 bool trylock()
00076 {
00077 int GoodLock = pthread_mutex_trylock(&m_mutex);
00078 return (GoodLock != EBUSY );
00079 }
00080 private:
00081 pthread_mutex_t m_mutex;
00082 };
00083
00084 typedef sync_ctrl_posix_mutex sync_ctrl_default;
00085
00086
00087 #endif //_WIN32
00088
00089 #endif
00090