Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion Framework/Core/include/Framework/DataProcessingStats.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<void(MetricSpec const&, int64_t, int64_t)> const& callback);

std::atomic<size_t> statesSize = 0;

std::array<Command, MAX_CMDS> cmds = {};
/// Held by processCommandQueue, so that the queue is flushed by one thread at a time.
std::mutex flushMutex;
std::array<int64_t, MAX_METRICS> metrics = {};
std::array<bool, MAX_METRICS> updated = {};
std::array<std::string, MAX_METRICS> metricsNames = {};
Expand Down
62 changes: 37 additions & 25 deletions Framework/Core/src/DataProcessingStats.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand All @@ -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<char, MAX_CMDS> 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;
}

Expand Down Expand Up @@ -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<void(DataProcessingStats::MetricSpec const&, int64_t, int64_t)> const& callback)
Expand Down
42 changes: 42 additions & 0 deletions Framework/Core/test/test_DataProcessingStats.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,11 @@
#include <catch_amalgamated.hpp>
#include <uv.h>

#include <atomic>
#include <chrono>
#include <memory>
#include <thread>

using namespace o2::framework;

enum TestMetricsId {
Expand Down Expand Up @@ -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<std::atomic<int>>(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);
}