Mt 0 0 1_Fill Histos

Fill histograms in parallel and write them on file. The simplest meaningful possible example which shows ROOT thread awareness.

Author: Danilo Piparo
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Thursday, March 04, 2021 at 09:54 AM.

Total amount of numbers

In [1]:
const UInt_t nNumbers = 20000000U;

The number of workers

In [2]:
const UInt_t nWorkers = 4U;

The first, fundamental operation to be performed in order to make root thread-aware.

In [3]:
ROOT::EnableThreadSafety();

We define our work item

In [4]:
auto workItem = [](UInt_t workerID) {
   // One generator, file and ntuple per worker
   TRandom3 workerRndm(workerID); // Change the seed
   TFile f(Form("myFile_mt001_%u.root", workerID), "RECREATE");
   TH1F h(Form("myHisto_%u", workerID), "The Histogram", 64, -4, 4);
   for (UInt_t i = 0; i < nNumbers; ++i) {
      h.Fill(workerRndm.Gaus());
   }
   h.Write();
};

Create the collection which will hold the threads, our "pool"

In [5]:
std::vector<std::thread> workers;

Fill the "pool" with workers

In [6]:
for (auto workerID : ROOT::TSeqI(nWorkers)) {
   workers.emplace_back(workItem, workerID);
}

Now join them

In [7]:
for (auto &&worker : workers)
   worker.join();

return 0;

Draw all canvases

In [8]:
gROOT->GetListOfCanvases()->Draw()