|
| 1 | +#include <conc/test.hpp> |
| 2 | + |
| 3 | +#include <catch2/catch_test_macros.hpp> |
| 4 | + |
| 5 | +#include <algorithm> |
| 6 | +#include <array> |
| 7 | +#include <chrono> |
| 8 | +#include <functional> |
| 9 | +#include <iterator> |
| 10 | +#include <random> |
| 11 | +#include <thread> |
| 12 | + |
| 13 | +TEST_CASE("test policy allows 'recursive' critical_sections", "[test_policy]") { |
| 14 | + auto const value = conc::call_in_critical_section( |
| 15 | + [] { return conc::call_in_critical_section([] { return 1; }); }); |
| 16 | + CHECK(value == 1); |
| 17 | +} |
| 18 | + |
| 19 | +namespace { |
| 20 | +struct rng_CS; |
| 21 | +struct count_CS; |
| 22 | + |
| 23 | +auto get_rng() -> auto & { |
| 24 | + std::array<int, std::mt19937::state_size> seed_data; |
| 25 | + std::random_device r; |
| 26 | + std::generate_n(seed_data.data(), seed_data.size(), std::ref(r)); |
| 27 | + std::seed_seq seq(std::begin(seed_data), std::end(seed_data)); |
| 28 | + static std::mt19937 rng(seq); |
| 29 | + return rng; |
| 30 | +} |
| 31 | +} // namespace |
| 32 | + |
| 33 | +TEST_CASE("test policy works", "[test_policy]") { |
| 34 | + conc::test_policy::reset_counts(); |
| 35 | + constexpr auto N = 10u; |
| 36 | + auto &rng = get_rng(); |
| 37 | + auto count = 0; |
| 38 | + auto dis = std::uniform_int_distribution{1, 10}; |
| 39 | + |
| 40 | + std::array<std::thread, N> threads{}; |
| 41 | + for (auto i = 0u; i < N; ++i) { |
| 42 | + threads[i] = std::thread{[&] { |
| 43 | + auto const d = conc::call_in_critical_section( |
| 44 | + [&] { return std::chrono::milliseconds{dis(rng)}; }); |
| 45 | + std::this_thread::sleep_for(d); |
| 46 | + conc::call_in_critical_section([&] { ++count; }); |
| 47 | + }}; |
| 48 | + } |
| 49 | + for (auto i = 0u; i < N; ++i) { |
| 50 | + threads[i].join(); |
| 51 | + } |
| 52 | + |
| 53 | + CHECK(count == N); |
| 54 | + CHECK(conc::test_policy::lock_count == N * 2); |
| 55 | + CHECK(conc::test_policy::unlock_count == N * 2); |
| 56 | +} |
| 57 | + |
| 58 | +TEST_CASE("test policy allows different-ID critical_sections", |
| 59 | + "[test_policy]") { |
| 60 | + auto &rng = get_rng(); |
| 61 | + auto count = 0; |
| 62 | + auto dis = std::uniform_int_distribution{1, 10}; |
| 63 | + |
| 64 | + auto t1 = std::thread{[&] { |
| 65 | + auto const d = conc::call_in_critical_section<rng_CS>( |
| 66 | + [&] { return std::chrono::milliseconds{dis(rng)}; }); |
| 67 | + std::this_thread::sleep_for(d); |
| 68 | + conc::call_in_critical_section<count_CS>([&] { ++count; }); |
| 69 | + }}; |
| 70 | + auto t2 = std::thread{[&] { |
| 71 | + auto const d = conc::call_in_critical_section<rng_CS>( |
| 72 | + [&] { return std::chrono::milliseconds{dis(rng)}; }); |
| 73 | + std::this_thread::sleep_for(d); |
| 74 | + conc::call_in_critical_section<count_CS>([&] { ++count; }); |
| 75 | + }}; |
| 76 | + t1.join(); |
| 77 | + t2.join(); |
| 78 | + |
| 79 | + CHECK(count == 2); |
| 80 | +} |
0 commit comments