Skip to content

Commit bead2f3

Browse files
committed
Add optimized variant for the common add_wrap(x, 1) case
1 parent ace6c92 commit bead2f3

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/consumer_queue.h

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ class consumer_queue {
9494
// Returns true if successful or false if queue full.
9595
template <class T> bool try_push(T &&sample) {
9696
std::size_t write_index = write_idx_.load(std::memory_order_acquire);
97-
std::size_t next_idx = add_wrap(write_index, 1);
97+
std::size_t next_idx = add1_wrap(write_index);
9898
item_t &item = buffer_[write_index % size_];
9999
if (UNLIKELY(write_index != item.seq_state.load(std::memory_order_acquire)))
100100
return false; // item currently occupied, queue full
@@ -112,7 +112,7 @@ class consumer_queue {
112112
for (;;) {
113113
item = &buffer_[read_index % size_];
114114
const std::size_t seq_state = item->seq_state.load(std::memory_order_acquire);
115-
const std::size_t next_idx = add_wrap(read_index, 1);
115+
const std::size_t next_idx = add1_wrap(read_index);
116116
// check if the item is ok to pop
117117
if (LIKELY(seq_state == next_idx)) {
118118
// yes, try to claim slot using CAS
@@ -137,12 +137,18 @@ class consumer_queue {
137137
// helper to either move or drop a value, depending on whether a dst argument is given
138138
inline static void move_or_drop(sample_p &src) { src.~sample_p(); }
139139
inline static void move_or_drop(sample_p &src, sample_p &dst) { dst = std::move(src); }
140-
// helper to add a delta to the given index and wrap correctly
140+
141+
/// helper to add a delta to the given index and wrap correctly
141142
FORCEINLINE std::size_t add_wrap(std::size_t x, std::size_t delta) const {
142143
const std::size_t xp = x + delta;
143144
return xp >= wrap_at_ ? xp - wrap_at_ : xp;
144145
}
145146

147+
/// helper to increment the given index, wrapping it if necessary
148+
inline std::size_t add1_wrap(std::size_t x) const {
149+
return ++x == wrap_at_ ? 0 : x;
150+
}
151+
146152
/// optional consumer registry
147153
send_buffer_p registry_;
148154
/// the sample buffer

0 commit comments

Comments
 (0)