aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/threading/unittests/recursive_spin_lock_ut.cpp
blob: 9c2d8f16cbf527225cb0401217430478b3f8d30a (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
79
80
81
82
83
84
85
86
87
88
#include <library/cpp/testing/gtest/gtest.h>

#include <library/cpp/yt/threading/recursive_spin_lock.h>
#include <library/cpp/yt/threading/event_count.h>

#include <thread>

namespace NYT::NThreading {
namespace {

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

TEST(TRecursiveSpinLockTest, SingleThread)
{
    TRecursiveSpinLock lock;
    EXPECT_FALSE(lock.IsLocked());
    EXPECT_TRUE(lock.TryAcquire());
    EXPECT_TRUE(lock.IsLocked());
    EXPECT_TRUE(lock.TryAcquire());
    EXPECT_TRUE(lock.IsLocked());
    lock.Release();
    EXPECT_TRUE(lock.IsLocked());
    lock.Release();
    EXPECT_FALSE(lock.IsLocked());
    EXPECT_TRUE(lock.TryAcquire());
    EXPECT_TRUE(lock.IsLocked());
    lock.Release();
    lock.Acquire();
    lock.Release();
}

TEST(TRecursiveSpinLockTest, TwoThreads)
{
    TRecursiveSpinLock lock;
    TEvent e1, e2, e3, e4, e5, e6, e7;

    std::thread t1([&] {
        e1.Wait();
        EXPECT_TRUE(lock.IsLocked());
        EXPECT_FALSE(lock.IsLockedByCurrentThread());
        EXPECT_FALSE(lock.TryAcquire());
        e2.NotifyOne();
        e3.Wait();
        EXPECT_TRUE(lock.IsLocked());
        EXPECT_FALSE(lock.IsLockedByCurrentThread());
        EXPECT_FALSE(lock.TryAcquire());
        e4.NotifyOne();
        e5.Wait();
        EXPECT_FALSE(lock.IsLocked());
        EXPECT_FALSE(lock.IsLockedByCurrentThread());
        EXPECT_TRUE(lock.TryAcquire());
        e6.NotifyOne();
        e7.Wait();
        lock.Release();
    });

    std::thread t2([&] {
        EXPECT_FALSE(lock.IsLocked());
        EXPECT_TRUE(lock.TryAcquire());
        EXPECT_TRUE(lock.IsLockedByCurrentThread());
        e1.NotifyOne();
        e2.Wait();
        EXPECT_TRUE(lock.TryAcquire());
        EXPECT_TRUE(lock.IsLockedByCurrentThread());
        e3.NotifyOne();
        e4.Wait();
        lock.Release();
        lock.Release();
        EXPECT_FALSE(lock.IsLocked());
        e5.NotifyOne();
        e6.Wait();
        EXPECT_TRUE(lock.IsLocked());
        EXPECT_FALSE(lock.IsLockedByCurrentThread());
        e7.NotifyOne();
        lock.Acquire();
        lock.Acquire();
        lock.Release();
        lock.Release();
    });

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

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

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