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.

111 lines
2.7 KiB

  1. /*****************************************************************************
  2. *
  3. * (C) COPYRIGHT MICROSOFT CORPORATION, 2000
  4. *
  5. * TITLE: w32utils.h
  6. *
  7. * VERSION: 1.0
  8. *
  9. * AUTHOR: LazarI
  10. *
  11. * DATE: 23-Dec-2000
  12. *
  13. * DESCRIPTION: Win32 templates & utilities (ported from printscan\ui\printui)
  14. *
  15. *****************************************************************************/
  16. #ifndef _W32UTILS_H
  17. #define _W32UTILS_H
  18. ////////////////////////////////////////////////
  19. //
  20. // template class CScopeLocker<TLOCK>
  21. //
  22. template <class TLOCK>
  23. class CScopeLocker
  24. {
  25. public:
  26. CScopeLocker(TLOCK &lock):
  27. m_Lock(lock), m_bLocked(false)
  28. { m_bLocked = (m_Lock && m_Lock.Lock()); }
  29. ~CScopeLocker()
  30. { if (m_bLocked) m_Lock.Unlock(); }
  31. operator bool () const
  32. { return m_bLocked; }
  33. private:
  34. bool m_bLocked;
  35. TLOCK &m_Lock;
  36. };
  37. ////////////////////////////////////////////////
  38. //
  39. // class CCSLock - win32 critical section lock.
  40. //
  41. class CCSLock
  42. {
  43. public:
  44. // CCSLock::Locker should be used as locker class.
  45. typedef CScopeLocker<CCSLock> Locker;
  46. CCSLock(): m_bInitialized(false)
  47. {
  48. __try
  49. {
  50. // InitializeCriticalSection may rise STATUS_NO_MEMORY exception
  51. // in low memory conditions (according the SDK)
  52. InitializeCriticalSection(&m_CS);
  53. m_bInitialized = true;
  54. return;
  55. }
  56. __except(EXCEPTION_EXECUTE_HANDLER) {}
  57. // if we end up here m_bInitialized will remain false
  58. // (i.e. out of memory exception was thrown)
  59. }
  60. ~CCSLock()
  61. {
  62. if (m_bInitialized)
  63. {
  64. // delete the critical section only if initialized successfully
  65. DeleteCriticalSection(&m_CS);
  66. }
  67. }
  68. operator bool () const
  69. {
  70. return m_bInitialized;
  71. }
  72. bool Lock()
  73. {
  74. __try
  75. {
  76. // EnterCriticalSection may rise STATUS_NO_MEMORY exception
  77. // in low memory conditions (this may happen if there is contention
  78. // and ntdll can't allocate the wait semaphore)
  79. EnterCriticalSection(&m_CS);
  80. return true;
  81. }
  82. __except(EXCEPTION_EXECUTE_HANDLER) {}
  83. // out of memory or invalid handle exception was thrown.
  84. return false;
  85. }
  86. void Unlock()
  87. {
  88. // Unlock() should be called *ONLY* if the corresponding
  89. // Lock() call has succeeded.
  90. LeaveCriticalSection(&m_CS);
  91. }
  92. private:
  93. bool m_bInitialized;
  94. CRITICAL_SECTION m_CS;
  95. };
  96. #endif // endif _W32UTILS_H