gstreamer
Loading...
Searching...
No Matches
multithread_root_tuples.cpp
Go to the documentation of this file.
1#include <TFile.h>
2#include <TTree.h>
3#include <ROOT/TThreadedObject.hxx>
4#include <TROOT.h>
5
6#include <thread>
7#include <mutex>
8#include <vector>
9#include <iostream>
10#include <string>
11
12// example of writing ROOT TTrees in multiple threads
13// to compile:
14// g++ -std=c++17 -O2 multithread_root_tuples.cpp $(root-config --cflags --libs) -o multithread_root_tuples
15
16
17// Mutex for thread-safe std::cout
18std::mutex cout_mutex;
19
20void writeTuple(int thread_id) {
21 std::string filename = "tuple_thread_" + std::to_string(thread_id) + ".root";
22
23 TFile file(filename.c_str(), "RECREATE");
24 if (file.IsZombie()) {
25 std::lock_guard<std::mutex> lock(cout_mutex);
26 std::cerr << "Error opening file: " << filename << std::endl;
27 return;
28 }
29
30 TTree tree("mytree", "Thread-safe example TTree");
31
32 std::vector<int> ids;
33 std::vector<float> values;
34
35 tree.Branch("ids", &ids);
36 tree.Branch("values", &values);
37
38 // AUTO FLUSH AND AUTOSAVE: flush every ~10 MB (adjust as needed)
39 tree.SetAutoFlush(10 * 1024 * 1024); // 10 MB
40 tree.SetAutoSave(30 * 1024 * 1024); // 30 MB autosave snapshots
41
42 const int total_events = 10000000;
43 for (int entry = 0; entry < total_events; ++entry) {
44 ids.clear();
45 values.clear();
46
47 int num_items = 10;
48 for (int i = 0; i < num_items; ++i) {
49 ids.push_back(entry * num_items + i);
50 values.push_back(1.23f * i + thread_id);
51 }
52
53 tree.Fill();
54 }
55
56 tree.Write(); // Write entire tree metadata and baskets
57 file.Close();
58
59 std::lock_guard<std::mutex> lock(cout_mutex);
60 std::cout << "Thread " << thread_id << " wrote file: " << filename << std::endl;
61}
62
63int main() {
64 ROOT::EnableThreadSafety();
65
66 const int num_threads = 8;
67 std::vector<std::thread> threads;
68
69 for (int i = 0; i < num_threads; ++i) {
70 threads.emplace_back(writeTuple, i);
71 }
72
73 for (auto& t : threads) {
74 t.join();
75 }
76
77 std::cout << "All threads finished writing ROOT files." << std::endl;
78 return 0;
79}
std::mutex cout_mutex
void writeTuple(int thread_id)