File indexing completed on 2023-03-17 11:01:51
0001 #include "FWCore/Concurrency/interface/ThreadSafeOutputFileStream.h"
0002
0003 #include <atomic>
0004 #include <sstream>
0005 #include <thread>
0006 #include <vector>
0007
0008 namespace {
0009
0010 std::atomic<int> nWaitingForThreads{};
0011
0012 void logToFile(unsigned const thread_index, edm::ThreadSafeOutputFileStream& f) {
0013 --nWaitingForThreads;
0014 while (nWaitingForThreads != 0)
0015 ;
0016
0017 std::ostringstream oss;
0018 oss << "Thread index: " << thread_index << " Entry: ";
0019 auto const& prefix = oss.str();
0020 for (int i{}; i < 4; ++i) {
0021 f.write(prefix + std::to_string(i) + "\n");
0022 }
0023 }
0024 }
0025
0026 int main() {
0027 edm::ThreadSafeOutputFileStream f{"thread_safe_ofstream_test.txt"};
0028 std::vector<std::thread> threads;
0029 unsigned const nThreads{3};
0030 nWaitingForThreads = nThreads;
0031 for (unsigned i{}; i < nThreads; ++i) {
0032 threads.emplace_back(logToFile, i, std::ref(f));
0033 }
0034
0035 for (auto& thread : threads)
0036 thread.join();
0037 }