Knowledge Base Nr: 00107 mutex.cpp - http://www.swe-kaiser.de

Downloads:

win32: mutex klasse und sample (prozess-synchronisation)

  
////////// header
class CMyMutex
{
public:
CMyMutex(const char* lpszName);
virtual ~CMyMutex();

bool Lock(int nWaitmSec); //true = ok; false = error
bool Unlock();

private:
HANDLE m_hMutex;
bool m_bLocked;
};

////////// source
CMyMutex::CMyMutex(const char* lpszName)
{
m_bLocked = false;

m_hMutex = ::CreateMutex(NULL, // no security attributes
FALSE, // initially not owned
lpszName); // name of mutex

if (m_hMutex == NULL)
{
ASSERT(FALSE);
DWORD dw = ::GetLastError();
}
}

CMyMutex::~CMyMutex()
{
if (m_hMutex)
::CloseHandle(m_hMutex);
}

bool CMyMutex::Lock(int nWaitmSec)
{
if (!m_hMutex)
return false;

if (m_bLocked)
return true;

DWORD dwWaitResult = ::WaitForSingleObject(m_hMutex, nWaitmSec);

switch (dwWaitResult)
{
case WAIT_OBJECT_0:
m_bLocked = true;
return true;

case WAIT_TIMEOUT: // Cannot get mutex ownership due to time-out.
return false;

case WAIT_ABANDONED: // Got ownership of the abandoned mutex object.
return false;
}

return false; //never reached?!
}

bool CMyMutex::Unlock()
{
if (!m_hMutex)
return false;

if (!m_bLocked)
return true;

if (!::ReleaseMutex(m_hMutex))
{
return false;
}

m_bLocked = false;
return true;
}

////////// sample usage
BOOL CMutextestDlg::OnInitDialog()
{
...
m_pmutex = new CMyMutex("LulliMutex");
...
}

void CMutextestDlg::OnButton1()
{
bool bSucc = m_pmutex->Lock(1000); //eine sekunde warten

GetDlgItem(IDC_STATE)->SetWindowText(bSucc ? "Locked!" : "Fehler beim Locken!");
}

void CMutextestDlg::OnButton2()
{
bool bSucc = m_pmutex->Unlock();

GetDlgItem(IDC_STATE)->SetWindowText(bSucc ? "UnLocked!" : "Fehler beim UnLocken!");
}