12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- // 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(TCHAR* name)
- {
- 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;
- }
- bool Unlock(HANDLE mutex)
- {
- if(0 == ReleaseMutex(mutex)) // Failed to release mutex
- {
- return false;
- }
- else // Successed in release mutex
- {
- CloseHandle(mutex);
- mutex = NULL;
- return true;
- }
- }
- //////////////////////////////////////////////////////////////////////
- // Construction/Destruction
- //////////////////////////////////////////////////////////////////////
- MyLock::MyLock(CString name)
- {
- m_handle=Lock((TCHAR*)(LPCTSTR)name);
- }
- MyLock::~MyLock()
- {
- Unlock(m_handle);
- }
|