Skip to content

Commit

Permalink
Added fence to counters to prevent data race
Browse files Browse the repository at this point in the history
  • Loading branch information
jakub-racek-swi committed Oct 15, 2024
1 parent dcf5718 commit 2ac2892
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 2 additions & 1 deletion util/counter_to_rate.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#pragma once

#include <utility>
#include <atomic>

#include <cstdlib>

Expand All @@ -18,7 +19,7 @@ template <typename T> struct CounterToRate {

constexpr CounterToRate(T data, T prev = {}) : value_{std::move(data)}, prev_{std::move(prev)}, count_{1} {}

constexpr T peek_rate() const { return value_ - prev_; }
constexpr T peek_rate() const { std::atomic_thread_fence(std::memory_order_acquire); return value_ - prev_; }
constexpr T commit_rate(bool empty_if_unitary = false);

constexpr T const &value() const { return value_; }
Expand Down
3 changes: 3 additions & 0 deletions util/counter_to_rate.inl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ namespace data {
template <typename T> constexpr T CounterToRate<T>::commit_rate(bool empty_if_unitary)
{
T choice[2] = {value_ - prev_, T{}};
std::atomic_thread_fence(std::memory_order_release);
prev_ = value_;

std::atomic_thread_fence(std::memory_order_acquire);
return choice[empty_if_unitary & (count_ < 2)];
}

Expand Down

0 comments on commit 2ac2892

Please sign in to comment.