Skip to content

Commit f1531b0

Browse files
committed
Dynamic lock-free fifo resize will force shrink to fit
1 parent d30191c commit f1531b0

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

util/lockfree_fifo_spsc_dyn.hh

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,14 +37,25 @@ public:
3737
, buf_(max_size_) {
3838
}
3939

40-
// Resets and resizes the vector. All contents are lost
41-
// max_size must be a power of 2 or else the next highest power of 2 will be used
40+
// Resets and resizes the vector. All contents are lost.
41+
// max_size must be a power of 2 or else the next highest power of 2 will be used.
42+
// If max_size does not change, do nothing.
4243
// Edge-case: max_size cannot be more than half the largest integer representable by size_t
43-
void resize(size_t max_size) {
44-
reset();
45-
max_size_ = MathTools::next_power_of_2(max_size);
46-
SIZE_MASK = max_size_ - 1;
47-
buf_.resize(max_size_);
44+
void resize(size_t new_max_size) {
45+
new_max_size = MathTools::next_power_of_2(new_max_size);
46+
if (new_max_size != max_size_) {
47+
reset();
48+
49+
if (new_max_size < max_size_) {
50+
// Deallocate the buffer to force shrink to fit
51+
std::vector<T>().swap(buf_);
52+
}
53+
54+
buf_.resize(new_max_size);
55+
56+
max_size_ = new_max_size;
57+
SIZE_MASK = max_size_ - 1;
58+
}
4859
}
4960

5061
//

0 commit comments

Comments
 (0)