CondSh.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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() : data(T()) {}
  19. CondSh(T t) : data(t) {}
  20. // set data
  21. void set(T t)
  22. {
  23. boost::unique_lock<boost::mutex> lock(mx);
  24. data = t;
  25. }
  26. // set data and notify
  27. void setn(T t)
  28. {
  29. set(t);
  30. cond.notify_all();
  31. };
  32. // get stored value
  33. T get()
  34. {
  35. boost::unique_lock<boost::mutex> lock(mx);
  36. return data;
  37. }
  38. // waits until data is set to false
  39. void waitWhileTrue()
  40. {
  41. boost::unique_lock<boost::mutex> un(mx);
  42. while(data)
  43. cond.wait(un);
  44. }
  45. // waits while data is set to arg
  46. void waitWhile(const T & t)
  47. {
  48. boost::unique_lock<boost::mutex> un(mx);
  49. while(data == t)
  50. cond.wait(un);
  51. }
  52. // waits until data is set to arg
  53. void waitUntil(const T & t)
  54. {
  55. boost::unique_lock<boost::mutex> un(mx);
  56. while(data != t)
  57. cond.wait(un);
  58. }
  59. };
  60. VCMI_LIB_NAMESPACE_END