mutex.cpp
00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #include "mutex.h"
00015
00016 #include "config.h"
00017
00018 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00019 # include <windows.h>
00020 #endif
00021
00022 #ifdef _WIN32_WCE
00023 # include <winbase.h>
00024 #endif
00025
00026 #ifdef HAVE_PTHREAD
00027 # include <pthread.h>
00028 #endif
00029
00030 namespace gloox
00031 {
00032
00033 namespace util
00034 {
00035
00036 class Mutex::MutexImpl
00037 {
00038 public:
00039 MutexImpl();
00040 ~MutexImpl();
00041 void lock();
00042 bool trylock();
00043 void unlock();
00044 private:
00045 MutexImpl( const MutexImpl& );
00046 MutexImpl& operator=( const MutexImpl& );
00047
00048 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00049 CRITICAL_SECTION m_cs;
00050 #elif defined( HAVE_PTHREAD )
00051 pthread_mutex_t m_mutex;
00052 #endif
00053
00054 };
00055
00056 Mutex::MutexImpl::MutexImpl()
00057 {
00058 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00059 InitializeCriticalSection( &m_cs );
00060 #elif defined( HAVE_PTHREAD )
00061 pthread_mutex_init( &m_mutex, 0 );
00062 #endif
00063 }
00064
00065 Mutex::MutexImpl::~MutexImpl()
00066 {
00067 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00068 DeleteCriticalSection( &m_cs );
00069 #elif defined( HAVE_PTHREAD )
00070 pthread_mutex_destroy( &m_mutex );
00071 #endif
00072 }
00073
00074 void Mutex::MutexImpl::lock()
00075 {
00076 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00077 EnterCriticalSection( &m_cs );
00078 #elif defined( HAVE_PTHREAD )
00079 pthread_mutex_lock( &m_mutex );
00080 #endif
00081 }
00082
00083 bool Mutex::MutexImpl::trylock()
00084 {
00085 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00086 return TryEnterCriticalSection( &m_cs ) ? true : false;
00087 #elif defined( HAVE_PTHREAD )
00088 return !( pthread_mutex_trylock( &m_mutex ) );
00089 #else
00090 return true;
00091 #endif
00092 }
00093
00094 void Mutex::MutexImpl::unlock()
00095 {
00096 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
00097 LeaveCriticalSection( &m_cs );
00098 #elif defined( HAVE_PTHREAD )
00099 pthread_mutex_unlock( &m_mutex );
00100 #endif
00101 }
00102
00103 Mutex::Mutex()
00104 : m_mutex( new MutexImpl() )
00105 {
00106 }
00107
00108 Mutex::~Mutex()
00109 {
00110 delete m_mutex;
00111 }
00112
00113 void Mutex::lock()
00114 {
00115 m_mutex->lock();
00116 }
00117
00118 bool Mutex::trylock()
00119 {
00120 return m_mutex->trylock();
00121 }
00122
00123 void Mutex::unlock()
00124 {
00125 m_mutex->unlock();
00126 }
00127
00128 }
00129
00130 }