Logo ROOT   6.08/07
Reference Guide
mt001_fillHistos.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_multicore
3 /// Fill histograms in parallel and write them on file.
4 /// The simplest meaningful possible example which shows ROOT thread awareness.
5 ///
6 /// \macro_code
7 ///
8 /// \author Danilo Piparo
9 /// \date January 2016
10 
11 // Total amount of numbers
12 const UInt_t nNumbers = 20000000U;
13 
14 // The number of workers
15 const UInt_t nWorkers = 4U;
16 
17 Int_t mt001_fillHistos()
18 {
19 
20  // The first, fundamental operation to be performed in order to make ROOT
21  // thread-aware.
23 
24  // We define our work item
25  auto workItem = [](UInt_t workerID) {
26  // One generator, file and ntuple per worker
27  TRandom3 workerRndm(workerID); // Change the seed
28  TFile f(Form("myFile_%u.root", workerID), "RECREATE");
29  TH1F h(Form("myHisto_%u", workerID), "The Histogram", 64, -4, 4);
30  for (UInt_t i = 0; i < nNumbers; ++i) {
31  h.Fill(workerRndm.Gaus());
32  }
33  h.Write();
34  };
35 
36  // Create the collection which will hold the threads, our "pool"
37  std::vector<std::thread> workers;
38 
39  // Fill the "pool" with workers
40  for (auto workerID : ROOT::TSeqI(nWorkers)) {
41  workers.emplace_back(workItem, workerID);
42  }
43 
44  // Now join them
45  for (auto && worker : workers) worker.join();
46 
47  return 0;
48 }
virtual Int_t Write(const char *name=0, Int_t option=0, Int_t bufsize=0)
Write this object to the current directory.
Definition: TObject.cxx:830
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3125
Random number generator class based on M.
Definition: TRandom3.h:29
TH1 * h
Definition: legend2.C:5
A ROOT file is a suite of consecutive data records (TKey instances) with a well defined format...
Definition: TFile.h:50
tomato 1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:575
int Int_t
Definition: RtypesCore.h:41
unsigned int UInt_t
Definition: RtypesCore.h:42
char * Form(const char *fmt,...)
double f(double x)
void EnableThreadSafety()
Enables the global mutex to make ROOT thread safe/aware.
Definition: TROOT.cxx:498
A pseudo container class which is a generator of indices.
Definition: TSeq.hxx:66