CountBarrierTest.cc 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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(): count(0)
  17. {
  18. }
  19. virtual ~CountBarrierTest()
  20. {
  21. }
  22. void Wait(CountBarrier& barrier)
  23. {
  24. barrier.Wait();
  25. }
  26. void Signal(CountBarrier& barrier)
  27. {
  28. boost::xtime xt;
  29. boost::xtime_get(&xt, boost::TIME_UTC);
  30. xt.sec += 2;
  31. boost::thread::sleep(xt);
  32. ++count;
  33. barrier.Signal();
  34. }
  35. };
  36. TEST_F(CountBarrierTest, Count)
  37. {
  38. CountBarrier barrier(10);
  39. ASSERT_EQ(10, barrier.Count());
  40. }
  41. TEST_F(CountBarrierTest, WaitAndSignal)
  42. {
  43. CountBarrier barrier(10);
  44. ThreadPool pool(10);
  45. for (int i = 0; i < 10; ++i)
  46. {
  47. pool.Schedule(
  48. boost::bind(&CountBarrierTest::Signal,
  49. this, boost::ref(barrier)));
  50. }
  51. ASSERT_EQ(0, this->count);
  52. barrier.Wait();
  53. ASSERT_EQ(10, this->count);
  54. pool.Wait();
  55. }
  56. } // namespace Egametang
  57. int main(int argc, char* argv[])
  58. {
  59. FLAGS_logtostderr = true;
  60. testing::InitGoogleTest(&argc, argv);
  61. google::ParseCommandLineFlags(&argc, &argv, true);
  62. google::InitGoogleLogging(argv[0]);
  63. return RUN_ALL_TESTS();
  64. }