count_down_latch_ut.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <library/cpp/testing/gtest/gtest.h>
  2. #include <library/cpp/yt/threading/count_down_latch.h>
  3. #include <thread>
  4. namespace NYT::NThreading {
  5. namespace {
  6. ////////////////////////////////////////////////////////////////////////////////
  7. void WaitForLatch(const TCountDownLatch& latch)
  8. {
  9. latch.Wait();
  10. EXPECT_EQ(0, latch.GetCount());
  11. }
  12. TEST(TCountDownLatch, TwoThreads)
  13. {
  14. TCountDownLatch latch(2);
  15. std::thread t1(std::bind(&WaitForLatch, std::cref(latch)));
  16. std::thread t2(std::bind(&WaitForLatch, std::cref(latch)));
  17. EXPECT_EQ(2, latch.GetCount());
  18. latch.CountDown();
  19. EXPECT_EQ(1, latch.GetCount());
  20. latch.CountDown();
  21. EXPECT_EQ(0, latch.GetCount());
  22. t1.join();
  23. t2.join();
  24. }
  25. TEST(TCountDownLatch, TwoThreadsPredecremented)
  26. {
  27. TCountDownLatch latch(2);
  28. EXPECT_EQ(2, latch.GetCount());
  29. latch.CountDown();
  30. EXPECT_EQ(1, latch.GetCount());
  31. latch.CountDown();
  32. EXPECT_EQ(0, latch.GetCount());
  33. std::thread t1(std::bind(&WaitForLatch, std::cref(latch)));
  34. std::thread t2(std::bind(&WaitForLatch, std::cref(latch)));
  35. t1.join();
  36. t2.join();
  37. }
  38. TEST(TCountDownLatch, TwoThreadsTwoLatches)
  39. {
  40. TCountDownLatch first(1);
  41. TCountDownLatch second(1);
  42. std::thread t1([&] () {
  43. first.Wait();
  44. second.CountDown();
  45. EXPECT_EQ(0, first.GetCount());
  46. EXPECT_EQ(0, second.GetCount());
  47. });
  48. std::thread t2([&] () {
  49. first.CountDown();
  50. second.Wait();
  51. EXPECT_EQ(0, first.GetCount());
  52. EXPECT_EQ(0, second.GetCount());
  53. });
  54. t1.join();
  55. t2.join();
  56. }
  57. ////////////////////////////////////////////////////////////////////////////////
  58. } // namespace
  59. } // namespace NYT::NThreading