diff --git a/Framework/Core/include/Framework/DataProcessingStats.h b/Framework/Core/include/Framework/DataProcessingStats.h index d5e9ec14adc26..0d2a796c477d7 100644 --- a/Framework/Core/include/Framework/DataProcessingStats.h +++ b/Framework/Core/include/Framework/DataProcessingStats.h @@ -188,13 +188,16 @@ struct DataProcessingStats { char const* findMetricNameById(ProcessingStatsId id) const; /// This will process the queue of commands required to update the stats. /// It is meant to be called periodically by a single thread. - void processCommandQueue(); + /// With @a onlyIfFull, it does nothing if the queue is not full once it has the lock. + void processCommandQueue(bool onlyIfFull = false); void flushChangedMetrics(std::function const& callback); std::atomic statesSize = 0; std::array cmds = {}; + /// Held by processCommandQueue, so that the queue is flushed by one thread at a time. + std::mutex flushMutex; std::array metrics = {}; std::array updated = {}; std::array metricsNames = {}; diff --git a/Framework/Core/src/DataProcessingStats.cxx b/Framework/Core/src/DataProcessingStats.cxx index 8349af62acdc2..849e75b3a9cb3 100644 --- a/Framework/Core/src/DataProcessingStats.cxx +++ b/Framework/Core/src/DataProcessingStats.cxx @@ -57,29 +57,21 @@ void DataProcessingStats::updateStats(CommandSpec cmd) pendingCmds++; // Add a static mutex to protect the queue // Get the next available operation in an atomic way. - auto idx = nextCmd.fetch_add(1, std::memory_order_relaxed); - if (idx == cmds.size()) { - // We abort this command + // Sequentially consistent, like the increment of pendingCmds above and, in + // processCommandQueue, the close of the queue and the read of pendingCmds which + // follows: either the flush sees this command pending and waits for it, or this + // thread sees the queue closed. It also acquires the release which reopens the + // queue, so that a command taken from a fresh queue is counted after + // insertedCmds was reset. + auto idx = nextCmd.fetch_add(1); + while (idx >= cmds.size()) { + // Full, or being flushed. Flush it, unless whoever was flushing it already + // has reopened it by the time we get the lock, and go round again. Not + // pending meanwhile: the flush waits for every pending command. pendingCmds--; - while (pendingCmds.load(std::memory_order_relaxed) > 0) { - // We need to wait for all the pending commands to be processed. - // This is needed because we are going to flush the queue. - // We cannot flush the queue while there are pending commands - // as we might end up with a command being processed twice. - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - processCommandQueue(); - insertedCmds.store(0, std::memory_order_relaxed); - nextCmd.store(0, std::memory_order_relaxed); + processCommandQueue(true); pendingCmds++; - idx = nextCmd.fetch_add(1, std::memory_order_relaxed); - } else if (idx > cmds.size()) { - while (cmds.size()) { - // We need to wait for the flushing of the queue - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - idx = nextCmd.load(std::memory_order_relaxed); - } - return updateStats(cmd); + idx = nextCmd.fetch_add(1); } // Save the command. assert(idx < cmds.size()); @@ -91,12 +83,34 @@ void DataProcessingStats::updateStats(CommandSpec cmd) updatedMetricsLapse++; } -void DataProcessingStats::processCommandQueue() +void DataProcessingStats::processCommandQueue(bool onlyIfFull) { + // With a thread pool, commands are added while this runs, and more than one + // thread may want to flush. So one flush at a time, and close the queue first: + // whoever takes a command from now on finds it full and waits here, while + // those who took one already finish writing it. + std::scoped_lock lock(flushMutex); + if (onlyIfFull && nextCmd.load() < cmds.size()) { + return; + } + nextCmd.exchange(cmds.size()); + while (pendingCmds.load() > 0) { + std::this_thread::yield(); + } + // Reopen in this order, so that nothing counted in the new queue is lost, and + // also if a command throws. + struct Reopen { + DataProcessingStats& stats; + ~Reopen() + { + stats.insertedCmds.store(0, std::memory_order_relaxed); + stats.nextCmd.store(0, std::memory_order_release); + } + } reopen{*this}; std::array order; // The range cannot be larger than the number of commands we have. auto range = insertedCmds.load(std::memory_order_relaxed); - if (insertedCmds.load(std::memory_order_relaxed) == 0) { + if (range == 0) { return; } @@ -196,8 +210,6 @@ void DataProcessingStats::processCommandQueue() } // No one should have tried to insert more commands while processing. assert(range == insertedCmds.load(std::memory_order_relaxed)); - nextCmd.store(0, std::memory_order_relaxed); - insertedCmds.store(0, std::memory_order_relaxed); } void DataProcessingStats::flushChangedMetrics(std::function const& callback) diff --git a/Framework/Core/test/test_DataProcessingStats.cxx b/Framework/Core/test/test_DataProcessingStats.cxx index 5f14ead966dc0..d07343edede07 100644 --- a/Framework/Core/test/test_DataProcessingStats.cxx +++ b/Framework/Core/test/test_DataProcessingStats.cxx @@ -16,6 +16,11 @@ #include #include +#include +#include +#include +#include + using namespace o2::framework; enum TestMetricsId { @@ -401,3 +406,40 @@ TEST_CASE("DataProcessingStatsPublishingRepeated") REQUIRE(updated.size() == 2); REQUIRE(count == 10); } + +TEST_CASE("DataProcessingStatsConcurrentUpdates") +{ + // With a thread pool, the loop and the pool threads update the same stats, so + // two of them regularly find the command queue full at once: one flushes it, + // the others have to wait for that and go on. Each thread adds 1 often enough + // to wrap the queue many times over, while one more flushes it directly, like + // the metrics flush on the loop; nothing may hang and nothing may be lost. + // Leaked and detached on purpose: if they hang, the test still fails in time. + auto* stats = new DataProcessingStats(TimingHelpers::defaultRealtimeBaseConfigurator(0, uv_default_loop()), + TimingHelpers::defaultCPUTimeConfigurator(uv_default_loop()), {}); + stats->registerMetric({.name = "dummy_metric", .metricId = DummyMetric}); + constexpr int THREADS = 4; + constexpr int UPDATES = 20000; + auto done = std::make_shared>(0); + for (int t = 0; t < THREADS; ++t) { + std::thread([stats, done]() { + for (int i = 0; i < UPDATES; ++i) { + stats->updateStats({DummyMetric, DataProcessingStats::Op::Add, 1}); + } + (*done)++; + }).detach(); + } + std::thread([stats, done]() { + while (*done < THREADS) { + stats->processCommandQueue(); + } + (*done)++; + }).detach(); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (*done <= THREADS && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + REQUIRE(*done == THREADS + 1); + stats->processCommandQueue(); + CHECK(stats->metrics[DummyMetric] == THREADS * UPDATES); +}