CountBarrierTest.cc 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 <boost/threadpool.hpp>
  6. #include <gtest/gtest.h>
  7. #include <glog/logging.h>
  8. #include <gflags/gflags.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 += 1;
  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. boost::threadpool::fifo_pool 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. testing::InitGoogleTest(&argc, argv);
  60. google::InitGoogleLogging(argv[0]);
  61. google::ParseCommandLineFlags(&argc, &argv, true);
  62. return RUN_ALL_TESTS();
  63. }