summaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/unittests/count_down_latch_ut.cpp
blob: 25ad5194ca3b5fa7995f3e96e625b242bcc5f91e (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
#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::jthread t1(std::bind(&WaitForLatch, std::cref(latch)));
    std::jthread 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());
}

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::jthread t1(std::bind(&WaitForLatch, std::cref(latch)));
    std::jthread t2(std::bind(&WaitForLatch, std::cref(latch)));
}

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

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

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

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

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