CountBarrierTest.cc 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 "Thread/ThreadPool.h"
  7. #include "Thread/CountBarrier.h"
  8. namespace Egametang {
  9. class CountBarrierTest: public testing::Test
  10. {
  11. protected:
  12. boost::detail::atomic_count count;
  13. public:
  14. CountBarrierTest(): count(0)
  15. {
  16. }
  17. virtual ~CountBarrierTest()
  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 += 1;
  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.Schedule(
  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. testing::InitGoogleTest(&argc, argv);
  58. return RUN_ALL_TESTS();
  59. }