• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
7 //[ guide_parallel_filling
8 
9 #include <boost/histogram.hpp>
10 #include <boost/histogram/algorithm/sum.hpp>
11 #include <cassert>
12 #include <functional>
13 #include <thread>
14 #include <vector>
15 
16 // dummy fill function, to be executed in parallel by several threads
17 template <typename Histogram>
fill(Histogram & h)18 void fill(Histogram& h) {
19   for (unsigned i = 0; i < 1000; ++i) { h(i % 10); }
20 }
21 
main()22 int main() {
23   using namespace boost::histogram;
24 
25   /*
26     Create histogram with container of thread-safe counters for parallel filling in
27     several threads. Only filling is thread-safe, other guarantees are not given.
28   */
29   auto h = make_histogram_with(dense_storage<accumulators::thread_safe<unsigned>>(),
30                                axis::integer<>(0, 10));
31 
32   /*
33     Run the fill function in parallel from different threads. This is safe when a
34     thread-safe accumulator and a storage with thread-safe cell access are used.
35   */
36   auto fill_h = [&h]() { fill(h); };
37   std::thread t1(fill_h);
38   std::thread t2(fill_h);
39   std::thread t3(fill_h);
40   std::thread t4(fill_h);
41   t1.join();
42   t2.join();
43   t3.join();
44   t4.join();
45 
46   // Without a thread-safe accumulator, this number may be smaller.
47   assert(algorithm::sum(h) == 4000);
48 }
49 
50 //]
51