Logo ROOT   6.07/09
Reference Guide
concurrentfill.cxx
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_v7
3 ///
4 /// \macro_code
5 ///
6 /// \date 2015-07-09
7 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!
8 /// \author Axel Naumann <axel@cern.ch>
9 
10 /*************************************************************************
11  * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers. *
12  * All rights reserved. *
13  * *
14  * For the licensing terms see $ROOTSYS/LICENSE. *
15  * For the list of contributors see $ROOTSYS/README/CREDITS. *
16  *************************************************************************/
17 
18 #include "ROOT/THist.hxx"
20 
21 #include <iostream>
22 #include <future>
23 #include <random>
24 
25 using namespace Experimental;
26 
27 double wasteCPUTime(std::mt19937& gen) {
28  // Simulate number crunching through gen and ridiculous num bits
29  return std::generate_canonical<double, 100>(gen)
30  + std::generate_canonical<double, 100>(gen)
31  + std::generate_canonical<double, 100>(gen)
32  + std::generate_canonical<double, 100>(gen)
33  + std::generate_canonical<double, 100>(gen);
34 }
35 
36 using Filler_t = Experimental::THistConcurrentFiller<Experimental::TH2D, 1024>;
37 
38 /// This function is called within each thread: it spends some CPU time and then
39 /// fills a number into the histogram, through the Filler_t. This is repeated
40 /// several times.
41 void theTask(Filler_t filler) {
42  std::mt19937 gen;
43 
44  for (int i = 0; i < 3000000; ++i)
45  filler.Fill({wasteCPUTime(gen), wasteCPUTime(gen)});
46 }
47 
48 /// This example fills a histogram concurrently, from several threads.
49 void concurrentHistFill(Experimental::TH2D& hist) {
50  // THistConcurrentFillManager allows multiple threads to fill the histogram
51  // concurrently.
52  //
53  // Details: each thread's Fill() calls are buffered. once the buffer is full,
54  // the THistConcurrentFillManager locks and flushes the buffer into the
55  // histogram.
56  Experimental::THistConcurrentFillManager<Experimental::TH2D> fillMgr(hist);
57 
58  std::array<std::thread, 8> threads;
59 
60  // Let the threads fill the histogram concurrently.
61  for (auto& thr: threads) {
62  // Each thread calls fill(), passing a dedicated filler per thread.
63  thr = std::thread(theTask, fillMgr.MakeFiller());
64  }
65 
66 
67  // Join them.
68  for (auto& thr: threads)
69  thr.join();
70 }
71 
72 void concurrentfill() {
73  // This histogram will be filled from several threads.
74  Experimental::TH2D hist{{100, 0., 1.}, {{0., 1., 2., 3.,10.}}};
75 
76  concurrentHistFill(hist);
77 
78  std::cout << hist.GetEntries() << '\n';
79 }
THist< 2, double, THistStatContent, THistStatUncertainty > TH2D
Definition: THist.hxx:307