From f3775dc2df0e927aa99c852fd2d8b613a33f91b0 Mon Sep 17 00:00:00 2001 From: Johannes Stoelp Date: Tue, 7 Nov 2023 21:51:26 +0100 Subject: mutex: add owning mutex utility --- test/owning_mutex.cc | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 test/owning_mutex.cc (limited to 'test/owning_mutex.cc') diff --git a/test/owning_mutex.cc b/test/owning_mutex.cc new file mode 100644 index 0000000..060415f --- /dev/null +++ b/test/owning_mutex.cc @@ -0,0 +1,41 @@ +#include + +#include +#include +#include + +#include +#include + +constexpr unsigned kNumThreads = 8; +constexpr unsigned kIter = 1 << 18; + +static_assert((static_cast(kNumThreads) * + static_cast(kIter)) <= + std::numeric_limits::max(), + "Expectate result overflowed!"); + +int main() { + owning_mutex data(0u); + + std::vector threads; + threads.reserve(kNumThreads); + + for (unsigned t = 0; t < kNumThreads; ++t) { + threads.emplace_back([&data, t]() { + for (unsigned i = 0; i < kIter; ++i) { + *data.lock() += 1; + } + std::printf("th%u finished\n", t); + }); + } + + for (auto& th : threads) { + th.join(); + } + + assert(*data.lock() == (kNumThreads * kIter)); + std::printf("Result %u\n", *data.lock()); + + return 0; +} -- cgit v1.2.3