aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/test/unit_tests/shmem.cpp
blob: 26f1389001c86f7da96d26a0ed57744823238df9 (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
// Copyright (c) 2020 Egor Tensin <Egor.Tensin@gmail.com>
// This file is part of the "winapi-common" project.
// For details, see https://github.com/egor-tensin/winapi-common.
// Distributed under the MIT License.

#include <winapi/shmem.hpp>

#include <boost/config.hpp>
#include <boost/test/unit_test.hpp>

#include <condition_variable>
#include <mutex>
#include <thread>

using namespace winapi;

namespace {

BOOST_CONSTEXPR_OR_CONST auto shmem_name = "test-data-struct";

BOOST_CONSTEXPR_OR_CONST int main_data = -1;
BOOST_CONSTEXPR_OR_CONST int setter1_data = 69;
BOOST_CONSTEXPR_OR_CONST int setter2_data = 420;

struct DataStruct {
    std::mutex mtx;
    std::condition_variable cv;
    int data;
};

void setter1_main() {
    const auto data_struct = SharedObject<DataStruct>::open(shmem_name);
    std::unique_lock<std::mutex> lck{data_struct->mtx};
    BOOST_TEST_MESSAGE(data_struct.ptr());

    data_struct->cv.wait(lck, [&]() { return data_struct->data == main_data; });
    data_struct->data = setter1_data;
    data_struct->cv.notify_all();
}

void setter2_main() {
    auto data_struct = SharedObject<DataStruct>::open(shmem_name);
    std::unique_lock<std::mutex> lck{data_struct->mtx};
    BOOST_TEST_MESSAGE(data_struct.ptr());

    data_struct->cv.wait(lck, [&]() { return data_struct->data == setter1_data; });
    data_struct->data = setter2_data;
    data_struct->cv.notify_all();
}

} // namespace

BOOST_AUTO_TEST_SUITE(shmem_tests)

BOOST_AUTO_TEST_CASE(basic) {
    auto data_struct = SharedObject<DataStruct>::create(shmem_name);

    std::thread setter1{&setter1_main};
    std::thread setter2{&setter2_main};
    {
        std::lock_guard<std::mutex> lck{data_struct->mtx};
        data_struct->data = main_data;
    }
    data_struct->cv.notify_all();

    setter1.join();
    setter2.join();

    BOOST_TEST(data_struct->data == setter2_data);
}

BOOST_AUTO_TEST_SUITE_END()