gloox  1.0
mutex.cpp
1 /*
2  Copyright (c) 2007-2009 by Jakob Schroeter <js@camaya.net>
3  This file is part of the gloox library. http://camaya.net/gloox
4 
5  This software is distributed under a license. The full license
6  agreement can be found in the file LICENSE in this distribution.
7  This software may not be copied, modified, sold or distributed
8  other than expressed in the named license agreement.
9 
10  This software is distributed without any warranty.
11 */
12 
13 
14 #include "mutex.h"
15 
16 #include "config.h"
17 
18 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
19 # include <windows.h>
20 #endif
21 
22 #ifdef _WIN32_WCE
23 # include <winbase.h>
24 #endif
25 
26 #ifdef HAVE_PTHREAD
27 # include <pthread.h>
28 #endif
29 
30 namespace gloox
31 {
32 
33  namespace util
34  {
35 
36  class Mutex::MutexImpl
37  {
38  public:
39  MutexImpl();
40  ~MutexImpl();
41  void lock();
42  bool trylock();
43  void unlock();
44  private:
45  MutexImpl( const MutexImpl& );
46  MutexImpl& operator=( const MutexImpl& );
47 
48 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
49  CRITICAL_SECTION m_cs;
50 #elif defined( HAVE_PTHREAD )
51  pthread_mutex_t m_mutex;
52 #endif
53 
54  };
55 
56  Mutex::MutexImpl::MutexImpl()
57  {
58 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
59  InitializeCriticalSection( &m_cs );
60 #elif defined( HAVE_PTHREAD )
61  pthread_mutex_init( &m_mutex, 0 );
62 #endif
63  }
64 
65  Mutex::MutexImpl::~MutexImpl()
66  {
67 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
68  DeleteCriticalSection( &m_cs );
69 #elif defined( HAVE_PTHREAD )
70  pthread_mutex_destroy( &m_mutex );
71 #endif
72  }
73 
75  {
76 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
77  EnterCriticalSection( &m_cs );
78 #elif defined( HAVE_PTHREAD )
79  pthread_mutex_lock( &m_mutex );
80 #endif
81  }
82 
84  {
85 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
86  return TryEnterCriticalSection( &m_cs ) ? true : false;
87 #elif defined( HAVE_PTHREAD )
88  return !( pthread_mutex_trylock( &m_mutex ) );
89 #else
90  return true;
91 #endif
92  }
93 
95  {
96 #if defined( _WIN32 ) && !defined( __SYMBIAN32__ )
97  LeaveCriticalSection( &m_cs );
98 #elif defined( HAVE_PTHREAD )
99  pthread_mutex_unlock( &m_mutex );
100 #endif
101  }
102 
104  : m_mutex( new MutexImpl() )
105  {
106  }
107 
109  {
110  delete m_mutex;
111  }
112 
113  void Mutex::lock()
114  {
115  m_mutex->lock();
116  }
117 
119  {
120  return m_mutex->trylock();
121  }
122 
124  {
125  m_mutex->unlock();
126  }
127 
128  }
129 
130 }