1
0

flagTracker.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. #include "main.h"
  2. #include "./flagTracker.h"
  3. FlagTracker::FlagTracker()
  4. : flags(0), cache(0), updateRef(0), eventHandler(NULL), eventParam(0)
  5. {
  6. InitializeCriticalSection(&lock);
  7. }
  8. FlagTracker::~FlagTracker()
  9. {
  10. DeleteCriticalSection(&lock);
  11. }
  12. void FlagTracker::Set(UINT nFlags, UINT nMask)
  13. {
  14. EnterCriticalSection(&lock);
  15. nFlags &= nMask;
  16. UINT clearMask = ~(nFlags ^ nMask);
  17. flags &= clearMask;
  18. cache &= clearMask;
  19. if (0 != nFlags)
  20. {
  21. Mark(nFlags);
  22. }
  23. LeaveCriticalSection(&lock);
  24. }
  25. UINT FlagTracker::Get()
  26. {
  27. return flags;
  28. }
  29. void FlagTracker::Mark(UINT nFlags)
  30. {
  31. EnterCriticalSection(&lock);
  32. flags |= nFlags;
  33. if (0 == updateRef)
  34. {
  35. if (NULL != eventHandler && 0 != nFlags)
  36. {
  37. eventHandler(nFlags, this, eventParam);
  38. }
  39. }
  40. else
  41. {
  42. cache |= nFlags;
  43. }
  44. LeaveCriticalSection(&lock);
  45. }
  46. ULONG FlagTracker::BeginUpdate()
  47. {
  48. EnterCriticalSection(&lock);
  49. ULONG r = InterlockedIncrement((LONG*)&updateRef);
  50. LeaveCriticalSection(&lock);
  51. return r;
  52. }
  53. ULONG FlagTracker::EndUpdate()
  54. {
  55. EnterCriticalSection(&lock);
  56. ULONG r;
  57. if (0 == updateRef)
  58. {
  59. r = 0;
  60. }
  61. else
  62. {
  63. r = InterlockedDecrement((LONG*)&updateRef);
  64. if (0 == r && 0 != cache)
  65. {
  66. Mark(cache);
  67. cache = 0;
  68. }
  69. }
  70. LeaveCriticalSection(&lock);
  71. return r;
  72. }
  73. void FlagTracker::SetEventHandler(EventHandler handler, ULONG_PTR user)
  74. {
  75. EnterCriticalSection(&lock);
  76. eventHandler = handler;
  77. eventParam = user;
  78. LeaveCriticalSection(&lock);
  79. }