aboutsummaryrefslogblamecommitdiff
path: root/test/owning_mutex.cc
blob: 060415f6dc7d194e1f76e2790ab546ad4a08fab8 (plain) (tree)








































                                                        
#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;
}