Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
mt304_fillHistos.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_multicore
3 /// \notebook -draw
4 /// Fill histograms in parallel with automatic binning.
5 /// Illustrates use of power-of-two autobin algorithm
6 ///
7 /// \macro_code
8 /// \macro_image
9 ///
10 /// \date November 2017
11 /// \author Gerardo Ganis
12 
13 // The number of workers
14 const UInt_t nWorkers = 8U;
15 
16 // Reference boundaries
17 const Double_t xmiref = -1.;
18 const Double_t xmaref = 7.;
19 
20 Int_t mt304_fillHistos(UInt_t nNumbers = 1001)
21 {
22 
23  // The first, fundamental operation to be performed in order to make ROOT
24  // thread-aware.
25  ROOT::EnableThreadSafety();
26 
27  // Histograms to be filled in parallel
28  ROOT::TThreadedObject<TH1D> h1d("h1d", "1D test histogram", 64, 0., -1.);
29  ROOT::TThreadedObject<TH1D> h1dr("h1dr", "1D test histogram w/ ref boundaries", 64, xmiref, xmaref);
30 
31  // We define our work item
32  auto workItem = [&](UInt_t workerID) {
33  // One generator, file and ntuple per worker
34  TRandom3 workerRndm(workerID); // Change the seed
35 
36  auto wh1d = h1d.Get();
37  wh1d->SetBit(TH1::kAutoBinPTwo);
38  auto wh1dr = h1dr.Get();
39 
40  Double_t x;
41  for (UInt_t i = 0; i < nNumbers; ++i) {
42  x = workerRndm.Gaus(3.);
43  wh1d->Fill(x);
44  wh1dr->Fill(x);
45  }
46  };
47 
48  // Create the collection which will hold the threads, our "pool"
49  std::vector<std::thread> workers;
50 
51  // Fill the "pool" with workers
52  for (auto workerID : ROOT::TSeqI(nWorkers)) {
53  workers.emplace_back(workItem, workerID);
54  }
55 
56  // Now join them
57  for (auto &&worker : workers)
58  worker.join();
59 
60  // Merge
61  auto fh1d = h1d.Merge();
62  auto fh1dr = h1dr.Merge();
63 
64  // Make the canvas
65  auto c = new TCanvas("c", "c", 800, 800);
66  c->Divide(1, 2);
67 
68  gStyle->SetOptStat(111110);
69  c->cd(1);
70  fh1d->DrawCopy();
71  c->cd(2);
72  fh1dr->DrawCopy();
73 
74  c->Update();
75 
76  return 0;
77 }