MyLock.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. mutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, name);
  16. if(NULL == mutex) // If the mutex does not exist, create it with the certain name.
  17. {
  18. mutex = CreateMutex(NULL, TRUE, name);
  19. }
  20. else // If the mutex already exist, wait for other thread release it.
  21. {
  22. WaitForSingleObject(mutex, INFINITE);
  23. }
  24. return mutex;
  25. }
  26. bool Unlock(HANDLE mutex)
  27. {
  28. if(0 == ReleaseMutex(mutex)) // Failed to release mutex
  29. {
  30. return false;
  31. }
  32. else // Successed in release mutex
  33. {
  34. CloseHandle(mutex);
  35. mutex = NULL;
  36. return true;
  37. }
  38. }
  39. //////////////////////////////////////////////////////////////////////
  40. // Construction/Destruction
  41. //////////////////////////////////////////////////////////////////////
  42. MyLock::MyLock(CString name)
  43. {
  44. m_handle=Lock((TCHAR*)(LPCTSTR)name);
  45. }
  46. MyLock::~MyLock()
  47. {
  48. Unlock(m_handle);
  49. }