ConditionalWait.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 ConditionalWait
  23. {
  24. bool isBusyValue = false;
  25. bool isTerminating = false;
  26. std::condition_variable cond;
  27. std::mutex mx;
  28. void set(bool value)
  29. {
  30. std::unique_lock lock(mx);
  31. isBusyValue = value;
  32. }
  33. public:
  34. ConditionalWait() = default;
  35. void setBusy()
  36. {
  37. set(true);
  38. }
  39. void setFree()
  40. {
  41. set(false);
  42. cond.notify_all();
  43. }
  44. void requestTermination()
  45. {
  46. isTerminating = true;
  47. setFree();
  48. }
  49. bool isBusy()
  50. {
  51. std::unique_lock lock(mx);
  52. return isBusyValue;
  53. }
  54. void waitWhileBusy()
  55. {
  56. std::unique_lock un(mx);
  57. cond.wait(un, [this](){ return !isBusyValue;});
  58. if (isTerminating)
  59. throw TerminationRequestedException();
  60. }
  61. };
  62. VCMI_LIB_NAMESPACE_END