CondSh.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. /*
  3. * CondSh.h, part of VCMI engine
  4. *
  5. * Authors: listed in file AUTHORS in main folder
  6. *
  7. * License: GNU General Public License v2.0 or later
  8. * Full text of license available in license.txt file, in main folder
  9. *
  10. */
  11. /// Used for multithreading, wraps boost functions
  12. template <typename T> struct CondSh
  13. {
  14. T data;
  15. boost::condition_variable cond;
  16. boost::mutex mx;
  17. CondSh() {}
  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. };