Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
mt103_fillNtupleFromMultipleThreads.C
Go to the documentation of this file.
1/// \file
2/// \ingroup tutorial_multicore
3/// \notebook
4/// Fill the same TNtuple from different threads.
5/// This tutorial illustrates the basics of how it's possible with ROOT
6/// to write simultaneously to a single output file using TBufferMerger.
7///
8/// \macro_code
9///
10/// \date May 2017
11/// \author Guilherme Amadio
12
13void mt103_fillNtupleFromMultipleThreads()
14{
15 // Avoid unnecessary output
16 gROOT->SetBatch();
17
18 // Make ROOT thread-safe
20
21 // Total number of events
22 const size_t nEntries = 65535;
23
24 // Match number of threads to what the hardware can do
25 const size_t nWorkers = 4;
26
27 // Split work in equal parts
28 const size_t nEventsPerWorker = nEntries / nWorkers;
29
30 // Create the TBufferMerger: this class orchestrates the parallel writing
31 auto fileName = "mt103_fillNtupleFromMultipleThreads.root";
32 ROOT::TBufferMerger merger(fileName);
33
34 // Define what each worker will do
35 // We obtain from a merger a TBufferMergerFile, which is nothing more than
36 // a file which is held in memory and that flushes to the TBufferMerger its
37 // content.
38 auto work_function = [&](int seed) {
39 auto f = merger.GetFile();
40 TNtuple ntrand("ntrand", "Random Numbers", "r");
41
42 TRandom rnd(seed);
43 for (auto i : ROOT::TSeqI(nEntries))
44 ntrand.Fill(rnd.Gaus());
45 f->Write();
46 };
47
48 // Create worker threads
49 std::vector<std::thread> workers;
50
51 for (auto i : ROOT::TSeqI(nWorkers))
52 workers.emplace_back(work_function, i + 1); // seed==0 means random seed :)
53
54 // Make sure workers are done
55 for (auto &&worker : workers)
56 worker.join();
57}
#define f(i)
Definition RSha256.hxx:104
#define gROOT
Definition TROOT.h:406
TBufferMerger is a class to facilitate writing data in parallel from multiple threads,...
A simple TTree restricted to a list of float variables only.
Definition TNtuple.h:28
This is the base class for the ROOT Random number generators.
Definition TRandom.h:27
Double_t Gaus(Double_t x, Double_t mean, Double_t sigma)
Gauss.
This file contains a specialised ROOT message handler to test for diagnostic in unit tests.
void EnableThreadSafety()
Enable support for multi-threading within the ROOT code in particular, enables the global mutex to ma...
Definition TROOT.cxx:499
TSeq< int > TSeqI
Definition TSeq.hxx:203