CondSh.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * CondSh.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. VCMI_LIB_NAMESPACE_BEGIN
  12. /// Used for multithreading, wraps boost functions
  13. template <typename T> struct CondSh
  14. {
  15. T data;
  16. boost::condition_variable cond;
  17. boost::mutex mx;
  18. CondSh(T t) : data(t) {}
  19. // set data
  20. void set(T t)
  21. {
  22. boost::unique_lock<boost::mutex> lock(mx);
  23. data = t;
  24. }
  25. // set data and notify
  26. void setn(T t)
  27. {
  28. set(t);
  29. cond.notify_all();
  30. };
  31. // get stored value
  32. T get()
  33. {
  34. boost::unique_lock<boost::mutex> lock(mx);
  35. return data;
  36. }
  37. // waits until data is set to false
  38. void waitWhileTrue()
  39. {
  40. boost::unique_lock<boost::mutex> un(mx);
  41. while(data)
  42. cond.wait(un);
  43. }
  44. // waits while data is set to arg
  45. void waitWhile(const T & t)
  46. {
  47. boost::unique_lock<boost::mutex> un(mx);
  48. while(data == t)
  49. cond.wait(un);
  50. }
  51. // waits until data is set to arg
  52. void waitUntil(const T & t)
  53. {
  54. boost::unique_lock<boost::mutex> un(mx);
  55. while(data != t)
  56. cond.wait(un);
  57. }
  58. };
  59. VCMI_LIB_NAMESPACE_END