CriticalLock.cpp 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "StdAfx.h"
  2. #include "CriticalLock.h"
  3. CCriticalLock::CCriticalLock(void)
  4. {
  5. m_bInitSucc = true;
  6. try
  7. {
  8. //带循环等待的初始化,推荐循环4000次
  9. if (!InitializeCriticalSectionAndSpinCount(&m_cs, 4000))
  10. {
  11. m_bInitSucc = false;
  12. }
  13. }
  14. catch (...)
  15. {
  16. m_bInitSucc = false;
  17. }
  18. }
  19. CCriticalLock::~CCriticalLock(void)
  20. {
  21. try
  22. {
  23. DeleteCriticalSection(&m_cs);
  24. }
  25. catch (...)
  26. {
  27. }
  28. }
  29. /******************************************************************************
  30. 加锁
  31. ******************************************************************************/
  32. bool CCriticalLock::Lock(void)
  33. {
  34. if (!m_bInitSucc)
  35. {
  36. return false;
  37. }
  38. try
  39. {
  40. EnterCriticalSection(&m_cs);
  41. }
  42. catch (...)
  43. {
  44. return false;
  45. }
  46. return true;
  47. }
  48. /******************************************************************************
  49. 解锁
  50. ******************************************************************************/
  51. bool CCriticalLock::Unlock(void)
  52. {
  53. if (!m_bInitSucc)
  54. {
  55. return false;
  56. }
  57. try
  58. {
  59. LeaveCriticalSection(&m_cs);
  60. }
  61. catch (...)
  62. {
  63. return false;
  64. }
  65. return true;
  66. }