Skip to content

Commit 67c865f

Browse files
committed
fix get last data
1 parent fe49dc8 commit 67c865f

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

include/slick_queue.h

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -138,19 +138,26 @@ class SlickQueue {
138138
}
139139

140140
/**
141-
* Read the last data in the queue
142-
*
143-
* This function is safe only for fixed sized data and alwasy reserve, publish one data at a time
141+
* Read the last published data in the queue
144142
*/
145143
T* read_last() noexcept {
146144
auto reserved = reserved_->load(std::memory_order_relaxed);
147-
auto index = reserved - 1;
148145
if (reserved == 0) {
149146
return nullptr;
150147
}
148+
auto index = reserved - 1;
151149

152-
// wait for the data published
153-
while (control_[index & mask_].data_index.load(std::memory_order_relaxed) != index);
150+
// find last published data
151+
auto begin = index & mask_;
152+
while (control_[index & mask_].data_index.load(std::memory_order_relaxed) != index)
153+
{
154+
--index;
155+
if ((index & mask_) == begin // looped entire queue
156+
|| index >= reserved) // passed 0
157+
{
158+
return nullptr;
159+
}
160+
}
154161
return &data_[index & mask_];
155162
}
156163

0 commit comments

Comments
 (0)