MyLock.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // MyLock.cpp: implementation of the MyLock class.
  2. //
  3. //////////////////////////////////////////////////////////////////////
  4. #include "stdafx.h"
  5. #include "MyLock.h"
  6. #ifdef _DEBUG
  7. #undef THIS_FILE
  8. static char THIS_FILE[]=__FILE__;
  9. #define new DEBUG_NEW
  10. #endif
  11. HANDLE Lock(TCHAR* name)
  12. {
  13. HANDLE mutex;
  14. // Try to open an exist mutex firstly.
  15. TCHAR szName[MAX_PATH] = {0};
  16. _stprintf_s(szName, _T("%s%d"), name, g_dwCSPort);
  17. mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, szName);
  18. if(NULL == mutex) // If the mutex does not exist, create it with the certain name.
  19. {
  20. mutex = CreateMutex(NULL, TRUE, szName);
  21. }
  22. else // If the mutex already exist, wait for other thread release it.
  23. {
  24. WaitForSingleObject(mutex, INFINITE);
  25. }
  26. return mutex;
  27. }
  28. bool Unlock(HANDLE mutex)
  29. {
  30. if(0 == ReleaseMutex(mutex)) // Failed to release mutex
  31. {
  32. return false;
  33. }
  34. else // Successed in release mutex
  35. {
  36. CloseHandle(mutex);
  37. mutex = NULL;
  38. return true;
  39. }
  40. }
  41. //////////////////////////////////////////////////////////////////////
  42. // Construction/Destruction
  43. //////////////////////////////////////////////////////////////////////
  44. MyLock::MyLock(CString name)
  45. {
  46. m_handle=Lock((TCHAR*)(LPCTSTR)name);
  47. }
  48. MyLock::~MyLock()
  49. {
  50. Unlock(m_handle);
  51. }