00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef INDRI_MUTEX_HPP
00019 #define INDRI_MUTEX_HPP
00020
00021 #include <assert.h>
00022
00023 #ifndef WIN32
00024 #include <pthread.h>
00025 #else
00026 #include "lemur-platform.h"
00027 #endif
00028
00029 #include "indri/Lockable.hpp"
00030 namespace indri
00031 {
00032 namespace thread
00033 {
00034
00035 class Mutex : public Lockable {
00036 friend class ConditionVariable;
00037
00038 private:
00039 #ifdef WIN32
00040 HANDLE _mutex;
00041 #else // POSIX
00042 pthread_mutex_t _mutex;
00043 #endif
00044
00045
00046 explicit Mutex( Mutex& m ) {}
00047
00048 public:
00049 Mutex() {
00050 #ifdef WIN32
00051 _mutex = ::CreateMutex( NULL, FALSE, NULL );
00052 #else
00053 pthread_mutex_init( &_mutex, NULL );
00054 #endif
00055 }
00056
00057 ~Mutex() {
00058 #ifdef WIN32
00059 if( _mutex != INVALID_HANDLE_VALUE ) {
00060 ::CloseHandle( _mutex );
00061 _mutex = 0;
00062 }
00063 #else
00064 pthread_mutex_destroy( &_mutex );
00065 #endif
00066 }
00067
00068 void lock() {
00069 #ifdef WIN32
00070 ::WaitForSingleObject( _mutex, INFINITE );
00071 #else
00072 int result = pthread_mutex_lock( &_mutex );
00073 assert( result == 0 );
00074 #endif
00075 }
00076
00077 bool tryLock() {
00078 #ifdef WIN32
00079 HRESULT result = ::WaitForSingleObject( _mutex, 0 );
00080 return (result == WAIT_OBJECT_0) || (result == WAIT_ABANDONED);
00081 #else
00082 return pthread_mutex_trylock( &_mutex ) == 0;
00083 #endif
00084 }
00085
00086 void unlock() {
00087 #ifdef WIN32
00088 ::ReleaseMutex( _mutex );
00089 #else
00090 int result = pthread_mutex_unlock( &_mutex );
00091 assert( result == 0 );
00092 #endif
00093 }
00094 };
00095 }
00096 }
00097
00098 #endif // INDRI_MUTEX_HPP
00099