Main Page | Namespace List | Class Hierarchy | Class List | File List | Namespace Members | Class Members | File Members | Related Pages

Mutex.hpp

Go to the documentation of this file.
00001 /*==========================================================================
00002  * Copyright (c) 2004 University of Massachusetts.  All Rights Reserved.
00003  *
00004  * Use of the Lemur Toolkit for Language Modeling and Information Retrieval
00005  * is subject to the terms of the software license set forth in the LICENSE
00006  * file included with this software, and also available at
00007  * http://www.lemurproject.org/license.html
00008  *
00009  *==========================================================================
00010  */
00011 
00012 //
00013 // Mutex
00014 //
00015 // 15 November 2004 -- tds
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       // make copy construction private
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 

Generated on Tue Jun 15 11:02:54 2010 for Lemur by doxygen 1.3.4