CondSh.h 1.2 KB

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