#ifndef WindowsMutex_h
#define WindowsMutex_h
#include <windows.h>
#include <string>
namespace CoreFW
{
class __declspec( dllexport ) FWMutex
{
private:
mutable HANDLE m_hMutex ;
unsigned long m_ulErrorCode ;
FWMutex( const FWMutex &MutexObject ) {}
void operator=( FWMutex &MutexObject ) {}
public:
FWMutex()
{
m_hMutex = CreateMutex( NULL, // no security attributes
FALSE, // initially not owned
NULL ) ; // name of mutex
m_ulErrorCode = GetLastError() ;
if( m_ulErrorCode == ERROR_INVALID_HANDLE )
m_hMutex = NULL ;
}
FWMutex( const std::string &strMutexName )
{
if( !strMutexName.empty() )
{
m_hMutex = CreateMutex( NULL, // no security attributes
FALSE, // initially not owned
strMutexName.c_str() ) ; // name of mutex
}
else
{
m_hMutex = CreateMutex( NULL, // no security attributes
FALSE, // initially not owned
NULL ) ; // name of mutex
}
m_ulErrorCode = GetLastError() ;
if( m_ulErrorCode == ERROR_INVALID_HANDLE )
m_hMutex = NULL ;
}
virtual ~FWMutex()
{
Unlock() ;
CloseHandle( m_hMutex ) ;
}
inline unsigned long GetMutexCreationErrorCode() const
{
return m_ulErrorCode ;
}
inline bool IsMutexAlreadyExist() const
{
return ( m_ulErrorCode == ERROR_ALREADY_EXISTS ) ;
}
inline bool IsMutexCreated() const
{
return ( m_hMutex != NULL ) ;
}
bool Lock() const
{
if( m_hMutex != NULL )
{
if( WaitForSingleObject( m_hMutex, INFINITE ) == WAIT_OBJECT_0 )
return true ;
}
return false ;
}
bool Unlock() const
{
if( m_hMutex != NULL )
{
if( ReleaseMutex( m_hMutex ) == TRUE )
return true ;
}
return false ;
}
} ;
} // End namespace
#endif // WindowsMutex_h