MyLock.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(char* name)
  12. {
  13. try
  14. {
  15. HANDLE mutex;
  16. // Try to open an exist mutex firstly.
  17. mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name);
  18. if(NULL == mutex) // If the mutex does not exist, create it with the certain name.
  19. {
  20. mutex = CreateMutex(NULL, TRUE, name);
  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. catch(...)
  29. {
  30. }
  31. }
  32. bool Unlock(HANDLE mutex)
  33. {
  34. try
  35. {
  36. if(0 == ReleaseMutex(mutex)) // Failed to release mutex
  37. {
  38. return false;
  39. }
  40. else // Successed in release mutex
  41. {
  42. CloseHandle(mutex);
  43. mutex = NULL;
  44. return true;
  45. }
  46. }
  47. catch(...)
  48. {
  49. }
  50. }
  51. //////////////////////////////////////////////////////////////////////
  52. // Construction/Destruction
  53. //////////////////////////////////////////////////////////////////////
  54. MyLock::MyLock(CString name)
  55. {
  56. m_handle=Lock((TCHAR*)(LPCTSTR)name);
  57. }
  58. MyLock::~MyLock()
  59. {
  60. Unlock(m_handle);
  61. }