ConditionalWait.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * ConditionalWait.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include <condition_variable>
  12. VCMI_LIB_NAMESPACE_BEGIN
  13. class TerminationRequestedException : public std::exception
  14. {
  15. public:
  16. using exception::exception;
  17. const char* what() const noexcept override
  18. {
  19. return "Thread termination requested";
  20. }
  21. };
  22. class ThreadInterruption
  23. {
  24. std::atomic<bool> interruptionRequested = false;
  25. public:
  26. void interruptionPoint()
  27. {
  28. bool result = interruptionRequested.exchange(false);
  29. if (result)
  30. throw TerminationRequestedException();
  31. }
  32. void interruptThread()
  33. {
  34. interruptionRequested.store(true);
  35. }
  36. void reset()
  37. {
  38. interruptionRequested.store(false);
  39. }
  40. };
  41. class ConditionalWait
  42. {
  43. bool isBusyValue = false;
  44. bool isTerminating = false;
  45. std::condition_variable cond;
  46. std::mutex mx;
  47. void set(bool value)
  48. {
  49. std::unique_lock lock(mx);
  50. isBusyValue = value;
  51. }
  52. public:
  53. ConditionalWait() = default;
  54. void setBusy()
  55. {
  56. set(true);
  57. }
  58. void setFree()
  59. {
  60. set(false);
  61. cond.notify_all();
  62. }
  63. void requestTermination()
  64. {
  65. isTerminating = true;
  66. setFree();
  67. }
  68. bool isBusy()
  69. {
  70. std::unique_lock lock(mx);
  71. return isBusyValue;
  72. }
  73. void waitWhileBusy()
  74. {
  75. std::unique_lock un(mx);
  76. cond.wait(un, [this](){ return !isBusyValue;});
  77. if (isTerminating)
  78. throw TerminationRequestedException();
  79. }
  80. };
  81. VCMI_LIB_NAMESPACE_END