Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.4 KiB

  1. class CTryableCriticalSection
  2. {
  3. public:
  4. CTryableCriticalSection();
  5. ~CTryableCriticalSection();
  6. public:
  7. void Lock();
  8. void Unlock();
  9. BOOL TryLock();
  10. private:
  11. BOOL TryLockPrivate(BOOL fTakeAlways);
  12. private:
  13. CRITICAL_SECTION m_csInner;
  14. CRITICAL_SECTION m_csOuter;
  15. LONG m_cRefs;
  16. };
  17. inline CTryableCriticalSection::CTryableCriticalSection()
  18. {
  19. InitializeCriticalSection(&m_csInner);
  20. InitializeCriticalSection(&m_csOuter);
  21. m_cRefs = 0;
  22. }
  23. inline CTryableCriticalSection::~CTryableCriticalSection()
  24. {
  25. DeleteCriticalSection(&m_csOuter);
  26. DeleteCriticalSection(&m_csInner);
  27. }
  28. inline void CTryableCriticalSection::Lock()
  29. {
  30. TryLockPrivate(TRUE);
  31. }
  32. inline void CTryableCriticalSection::Unlock()
  33. {
  34. LeaveCriticalSection(&m_csInner);
  35. InterlockedDecrement(&m_cRefs);
  36. }
  37. inline BOOL CTryableCriticalSection::TryLock()
  38. {
  39. return TryLockPrivate(FALSE);
  40. }
  41. inline BOOL CTryableCriticalSection::TryLockPrivate(BOOL fTakeAlways)
  42. {
  43. BOOL fLocked = FALSE;
  44. EnterCriticalSection(&m_csOuter);
  45. if (fTakeAlways || !m_cRefs)
  46. {
  47. fLocked = TRUE;
  48. InterlockedIncrement(&m_cRefs);
  49. EnterCriticalSection(&m_csInner);
  50. }
  51. LeaveCriticalSection(&m_csOuter);
  52. return fLocked;
  53. }