CondSh.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #ifndef __CONDSH_H__
  2. #define __CONDSH_H__
  3. #include <boost/thread.hpp>
  4. /*
  5. * CondSh.h, part of VCMI engine
  6. *
  7. * Authors: listed in file AUTHORS in main folder
  8. *
  9. * License: GNU General Public License v2.0 or later
  10. * Full text of license available in license.txt file, in main folder
  11. *
  12. */
  13. /// Used for multithreading, wraps boost functions
  14. template <typename T> struct CondSh
  15. {
  16. T data;
  17. boost::condition_variable cond;
  18. boost::mutex mx;
  19. CondSh()
  20. {}
  21. CondSh(T t)
  22. {
  23. data = t;
  24. }
  25. void set(T t)
  26. {
  27. mx.lock();
  28. data=t;
  29. mx.unlock();
  30. }
  31. void setn(T t) //set data and notify
  32. {
  33. mx.lock();
  34. data=t;
  35. mx.unlock();
  36. cond.notify_all();
  37. };
  38. T get() //get stored value
  39. {
  40. boost::unique_lock<boost::mutex> lock(mx);
  41. return data;
  42. }
  43. void waitWhileTrue() //waits until data is set to false
  44. {
  45. boost::unique_lock<boost::mutex> un(mx);
  46. while(data)
  47. cond.wait(un);
  48. }
  49. void waitWhile(const T &t) //waits while data is set to arg
  50. {
  51. boost::unique_lock<boost::mutex> un(mx);
  52. while(data == t)
  53. cond.wait(un);
  54. }
  55. void waitUntil(const T &t) //waits until data is set to arg
  56. {
  57. boost::unique_lock<boost::mutex> un(mx);
  58. while(data != t)
  59. cond.wait(un);
  60. }
  61. };
  62. #endif // __CONDSH_H__