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
#include <mutex>
#include <thread>
#include <vector>
#include <printf.hpp>
#include <hpc/aux/walltime.hpp>

class Counter {
   public:
      using Value = unsigned long long int;

      Counter() : counter(0) {
      }
      auto increment() {
	 std::lock_guard<std::mutex> lock(mutex);
	 return ++counter;
      }
   private:
      std::mutex mutex;
      Value counter;
};

int main() {
   constexpr unsigned int nof_threads = 2;
   constexpr Counter::Value max_counter = 1LL << 24;

   std::vector<std::thread> threads(nof_threads);
   hpc::aux::WallTime<double> wall_time;
   Counter counter;
   wall_time.tic();
      for (auto& t: threads) {
	 t = std::thread([&]{
	    while (counter.increment() < max_counter)
	       ;
	 });
      }
      for (auto& t: threads) {
	 t.join();
      }
   auto t = wall_time.toc();
   fmt::printf("avg time per lock = %.2lf ns\n",
      t / max_counter * 1000000000LL);
}