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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
// Copyright 2023 Peter Dimov.
// Copyright 2023 Christian Mazakas.
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#define BOOST_ENABLE_ASSERT_HANDLER
#include <boost/compat/latch.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/core/lightweight_test.hpp>
#include <thread>
#include <vector>
struct exception {};
namespace boost {
void assertion_failed(char const *expr, char const *function, char const *file,
long line) {
(void)expr;
(void)function;
(void)file;
(void)line;
throw exception{};
}
} // namespace boost
namespace {
void test_max() { BOOST_TEST_EQ(boost::compat::latch::max(), PTRDIFF_MAX); }
void test_constructor() {
{
auto const f = [] {
boost::compat::latch l(-1);
(void)l;
};
BOOST_TEST_THROWS(f(), exception);
}
{
std::ptrdiff_t n = 0;
boost::compat::latch l(n);
BOOST_TEST(l.try_wait());
}
{
std::ptrdiff_t n = 16;
boost::compat::latch l(n);
BOOST_TEST_NOT(l.try_wait());
l.count_down(16);
BOOST_TEST(l.try_wait());
}
{
auto const f = [] {
std::ptrdiff_t n = boost::compat::latch::max();
boost::compat::latch l(n);
(void)l;
};
BOOST_TEST_NO_THROW(f());
}
}
void test_count_down_and_wait() {
constexpr std::ptrdiff_t n = 1024;
boost::compat::latch l(2 * n);
bool bs[] = {false, false};
std::thread t1([&] {
l.wait();
BOOST_TEST(bs[0]);
BOOST_TEST(bs[1]);
});
std::thread t2([&] {
for (int i = 0; i < n; ++i) {
if (i == (n - 1)) {
bs[0] = true;
} else {
BOOST_TEST_NOT(l.try_wait());
}
l.count_down(1);
}
});
for (int i = 0; i < n; ++i) {
if (i == (n - 1)) {
bs[1] = true;
} else {
BOOST_TEST_NOT(l.try_wait());
}
l.count_down(1);
}
t1.join();
t2.join();
BOOST_TEST(l.try_wait());
}
void test_arrive_and_wait() {
std::ptrdiff_t const n = 16;
boost::compat::latch l(2 * n);
int xs[n] = {0};
std::vector<std::thread> threads;
for (int i = 0; i < n; ++i) {
threads.emplace_back([&l, &xs, i, n] {
// keep this here because msvc requires a capture but clang calls it
// redundant
boost::ignore_unused(n);
for (int j = 0; j < n; ++j) {
BOOST_TEST_EQ(xs[j], 0);
}
l.arrive_and_wait(2);
xs[i] = 1;
});
}
for (auto &t : threads) {
t.join();
}
for (int i = 0; i < n; ++i) {
BOOST_TEST_EQ(xs[i], 1);
}
}
} // namespace
int main() {
test_max();
test_constructor();
test_count_down_and_wait();
test_arrive_and_wait();
return boost::report_errors();
}
|