aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/unittests/count_down_latch_ut.cpp
blob: 894bdab22a71803c9f74a3e6407268ad67a4c8ff (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <library/cpp/testing/gtest/gtest.h>

#include <library/cpp/yt/threading/count_down_latch.h>

#include <thread>

namespace NYT::NThreading {
namespace {

////////////////////////////////////////////////////////////////////////////////

void WaitForLatch(const TCountDownLatch& latch)
{
    latch.Wait();
    EXPECT_EQ(0, latch.GetCount());
}

TEST(TCountDownLatch, TwoThreads)
{
    TCountDownLatch latch(2);

    std::thread t1(std::bind(&WaitForLatch, std::cref(latch)));
    std::thread t2(std::bind(&WaitForLatch, std::cref(latch)));

    EXPECT_EQ(2, latch.GetCount());
    latch.CountDown();
    EXPECT_EQ(1, latch.GetCount());
    latch.CountDown();
    EXPECT_EQ(0, latch.GetCount());

    t1.join();
    t2.join();
}

TEST(TCountDownLatch, TwoThreadsPredecremented)
{
    TCountDownLatch latch(2);

    EXPECT_EQ(2, latch.GetCount());
    latch.CountDown();
    EXPECT_EQ(1, latch.GetCount());
    latch.CountDown();
    EXPECT_EQ(0, latch.GetCount());

    std::thread t1(std::bind(&WaitForLatch, std::cref(latch)));
    std::thread t2(std::bind(&WaitForLatch, std::cref(latch)));

    t1.join();
    t2.join();
}

TEST(TCountDownLatch, TwoThreadsTwoLatches)
{
    TCountDownLatch first(1);
    TCountDownLatch second(1);

    std::thread t1([&] () {
        first.Wait();
        second.CountDown();
        EXPECT_EQ(0, first.GetCount());
        EXPECT_EQ(0, second.GetCount());
    });

    std::thread t2([&] () {
        first.CountDown();
        second.Wait();
        EXPECT_EQ(0, first.GetCount());
        EXPECT_EQ(0, second.GetCount());
    });

    t1.join();
    t2.join();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace
} // namespace NYT::NThreading