CountBarrierTest.cc 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. pool.Start();
  44. for (int i = 0; i < 10; ++i)
  45. {
  46. pool.PushTask(
  47. boost::bind(&CountBarrierTest::Signal,
  48. this, boost::ref(barrier)));
  49. }
  50. ASSERT_EQ(0, this->count_);
  51. barrier.Wait();
  52. ASSERT_EQ(10, this->count_);
  53. pool.Stop();
  54. }
  55. } // namespace Egametang
  56. int main(int argc, char* argv[])
  57. {
  58. FLAGS_logtostderr = true;
  59. testing::InitGoogleTest(&argc, argv);
  60. google::ParseCommandLineFlags(&argc, &argv, true);
  61. google::InitGoogleLogging(argv[0]);
  62. return RUN_ALL_TESTS();
  63. }