aboutsummaryrefslogtreecommitdiff
path: root/test/owning_mutex.cc
diff options
context:
space:
mode:
authorJohannes Stoelp <johannes.stoelp@gmail.com>2023-11-07 21:51:26 +0100
committerJohannes Stoelp <johannes.stoelp@gmail.com>2023-11-07 21:51:26 +0100
commitf3775dc2df0e927aa99c852fd2d8b613a33f91b0 (patch)
tree2ab08edf2e155198982c2b236f8d62512f33e4ec /test/owning_mutex.cc
parent0eb531749a805e1d83c856e6c59503af506f4d3c (diff)
downloadcpp-utils-f3775dc2df0e927aa99c852fd2d8b613a33f91b0.tar.gz
cpp-utils-f3775dc2df0e927aa99c852fd2d8b613a33f91b0.zip
mutex: add owning mutex utility
Diffstat (limited to 'test/owning_mutex.cc')
-rw-r--r--test/owning_mutex.cc41
1 files changed, 41 insertions, 0 deletions
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 <owning_mutex.h>
+
+#include <limits>
+#include <thread>
+#include <vector>
+
+#include <cassert>
+#include <cstdio>
+
+constexpr unsigned kNumThreads = 8;
+constexpr unsigned kIter = 1 << 18;
+
+static_assert((static_cast<unsigned long>(kNumThreads) *
+ static_cast<unsigned long>(kIter)) <=
+ std::numeric_limits<unsigned>::max(),
+ "Expectate result overflowed!");
+
+int main() {
+ owning_mutex<unsigned> data(0u);
+
+ std::vector<std::thread> 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;
+}