CountBarrierTest.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include <boost/bind.hpp>
  2. #include <boost/ref.hpp>
  3. #include <boost/detail/atomic_count.hpp>
  4. #include <boost/date_time.hpp>
  5. #include <gtest/gtest.h>
  6. #include <glog/logging.h>
  7. #include <gflags/gflags.h>
  8. #include "Thread/ThreadPool.h"
  9. #include "Thread/CountBarrier.h"
  10. namespace Egametang {
  11. class CountBarrierTest: public testing::Test
  12. {
  13. protected:
  14. boost::detail::atomic_count count_;
  15. public:
  16. CountBarrierTest():
  17. count_(0)
  18. {
  19. }
  20. void Wait(CountBarrier& barrier)
  21. {
  22. barrier.Wait();
  23. }
  24. void Signal(CountBarrier& barrier)
  25. {
  26. boost::xtime xt;
  27. boost::xtime_get(&xt, boost::TIME_UTC);
  28. xt.sec += 2;
  29. boost::thread::sleep(xt);
  30. ++count_;
  31. barrier.Signal();
  32. }
  33. };
  34. TEST_F(CountBarrierTest, Count)
  35. {
  36. CountBarrier barrier(10);
  37. ASSERT_EQ(10, barrier.Count());
  38. }
  39. TEST_F(CountBarrierTest, WaitAndSignal)
  40. {
  41. CountBarrier barrier(10);
  42. ThreadPool pool(10);
  43. for (int i = 0; i < 10; ++i)
  44. {
  45. pool.PushTask(
  46. boost::bind(&CountBarrierTest::Signal,
  47. this, boost::ref(barrier)));
  48. }
  49. ASSERT_EQ(0, this->count_);
  50. barrier.Wait();
  51. ASSERT_EQ(10, this->count_);
  52. pool.Wait();
  53. }
  54. } // namespace Egametang
  55. int main(int argc, char* argv[])
  56. {
  57. FLAGS_logtostderr = true;
  58. testing::InitGoogleTest(&argc, argv);
  59. google::ParseCommandLineFlags(&argc, &argv, true);
  60. google::InitGoogleLogging(argv[0]);
  61. return RUN_ALL_TESTS();
  62. }