/***************************************************************************
                             Mutex.h
                             -------------------
    Begin                : Thu Oct 26, 2001
    Objective            : Basic Object Synchronization Class
    Author               : Drew Hall
    Email                : dhall@Zero-Soft.com
 ***************************************************************************/
#include "stdafx.h"

CMutex::CMutex(const TCHAR* szName, bool bLockMutex)
{
   assert(strlen(szName) != 0);
   
   m_szMutexName = new TCHAR[strlen(szName)+1];
   strcpy(m_szMutexName, szName);

   m_hMutex = OpenMutex(MUTEX_ALL_ACCESS, true, szName);       // Try to open it
   if(!m_hMutex)
      m_hMutex = CreateMutex(NULL, bLockMutex, szName);     // Mutex doesn't exist, therefore this is the only instance
   else
      throw(CException(12, "Couldn't create instance, another version is running!", __LINE__, __FILE__));

   m_hMutex = CreateMutex(NULL, bLockMutex, szName);
}

CMutex::~CMutex()
{
   ::ReleaseMutex(m_hMutex);
   delete[] m_szMutexName;
}

bool CMutex::AcquireMutex()
{
   m_hMutex = OpenMutex(MUTEX_ALL_ACCESS, true, m_szMutexName);
   return (m_hMutex != NULL);
}

bool CMutex::ReleaseMutex()
{
   return ::ReleaseMutex(m_hMutex);
}
