123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- // 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);
- }
|