guide_parallel_filling.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. // Copyright 2018-2019 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //[ guide_parallel_filling
  7. #include <boost/histogram.hpp>
  8. #include <boost/histogram/algorithm/sum.hpp>
  9. #include <cassert>
  10. #include <functional>
  11. #include <thread>
  12. #include <vector>
  13. // dummy fill function, to be executed in parallel by several threads
  14. template <typename Histogram>
  15. void fill(Histogram& h) {
  16. for (unsigned i = 0; i < 1000; ++i) { h(i % 10); }
  17. }
  18. int main() {
  19. using namespace boost::histogram;
  20. /*
  21. Create histogram with container of thread-safe counters for parallel filling in
  22. several threads. Only filling is thread-safe, other guarantees are not given.
  23. */
  24. auto h = make_histogram_with(dense_storage<accumulators::thread_safe<unsigned>>(),
  25. axis::integer<>(0, 10));
  26. /*
  27. Run the fill function in parallel from different threads. This is safe when a
  28. thread-safe accumulator and a storage with thread-safe cell access are used.
  29. */
  30. auto fill_h = [&h]() { fill(h); };
  31. std::thread t1(fill_h);
  32. std::thread t2(fill_h);
  33. std::thread t3(fill_h);
  34. std::thread t4(fill_h);
  35. t1.join();
  36. t2.join();
  37. t3.join();
  38. t4.join();
  39. // Without a thread-safe accumulator, this number may be smaller.
  40. assert(algorithm::sum(h) == 4000);
  41. }
  42. //]