// MyLock.cpp: implementation of the MyLock class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyLock.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif HANDLE Lock(char* name) { try { HANDLE mutex; // Try to open an exist mutex firstly. mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name); if(NULL == mutex) // If the mutex does not exist, create it with the certain name. { mutex = CreateMutex(NULL, TRUE, name); } else // If the mutex already exist, wait for other thread release it. { WaitForSingleObject(mutex, INFINITE); } return mutex; } catch(...) { } } bool Unlock(HANDLE mutex) { try { if(0 == ReleaseMutex(mutex)) // Failed to release mutex { return false; } else // Successed in release mutex { CloseHandle(mutex); mutex = NULL; return true; } } catch(...) { } } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// MyLock::MyLock(CString name) { m_handle=Lock((TCHAR*)(LPCTSTR)name); } MyLock::~MyLock() { Unlock(m_handle); }