CondSh.h 1.2 KB

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