Fix size count in TSLQueue when using iterator

This commit is contained in:
Stephen Seo 2019-11-06 13:32:39 +09:00
parent 3f338be365
commit a5873624aa
2 changed files with 18 additions and 4 deletions

View file

@ -62,7 +62,8 @@ class TSLQueue {
class TSLQIter {
public:
TSLQIter(std::mutex &mutex,
std::weak_ptr<TSLQNode> currentNode);
std::weak_ptr<TSLQNode> currentNode,
unsigned long long *msize);
~TSLQIter();
std::optional<T> current();
@ -73,6 +74,8 @@ class TSLQueue {
private:
std::lock_guard<std::mutex> lock;
std::weak_ptr<TSLQNode> currentNode;
unsigned long long *msize;
};
public:
@ -273,9 +276,11 @@ bool TSLQueue<T>::TSLQNode::isNormal() const {
template <typename T>
TSLQueue<T>::TSLQIter::TSLQIter(std::mutex &mutex,
std::weak_ptr<TSLQNode> currentNode) :
std::weak_ptr<TSLQNode> currentNode,
unsigned long long *msize) :
lock(mutex),
currentNode(currentNode)
currentNode(currentNode),
msize(msize)
{
}
@ -335,12 +340,15 @@ bool TSLQueue<T>::TSLQIter::remove() {
currentNode->next->prev = parent;
parent->next = currentNode->next;
assert(*msize > 0);
--(*msize);
return parent->next->isNormal();
}
template <typename T>
typename TSLQueue<T>::TSLQIter TSLQueue<T>::begin() {
return TSLQIter(mutex, head->next);
return TSLQIter(mutex, head->next, &msize);
}
#endif

View file

@ -123,6 +123,7 @@ TEST(TSLQueue, Iterator) {
for(int i = 0; i < 10; ++i) {
q.push(i);
}
EXPECT_EQ(q.size(), 10);
{
// iteration
@ -175,6 +176,7 @@ TEST(TSLQueue, Iterator) {
EXPECT_TRUE(op.has_value());
EXPECT_EQ(op.value(), 2);
}
EXPECT_EQ(q.size(), 9);
// check that "3" was removed from queue
int i = 0;
@ -194,10 +196,12 @@ TEST(TSLQueue, Iterator) {
q.push(1);
q.push(2);
q.push(3);
EXPECT_EQ(q.size(), 4);
{
auto iter = q.begin();
EXPECT_TRUE(iter.remove());
}
EXPECT_EQ(q.size(), 3);
i = 1;
while(!q.empty()) {
op = q.top();
@ -211,6 +215,7 @@ TEST(TSLQueue, Iterator) {
q.push(1);
q.push(2);
q.push(3);
EXPECT_EQ(q.size(), 4);
{
auto iter = q.begin();
while(true) {
@ -223,6 +228,7 @@ TEST(TSLQueue, Iterator) {
}
}
}
EXPECT_EQ(q.size(), 3);
i = 0;
while(!q.empty()) {
op = q.top();