CondSh.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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(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. };