Skip to content

Commit

Permalink
AtomicLinkedList::sweepOnce for a reversed single list sweep
Browse files Browse the repository at this point in the history
Summary: reverseSweep's semantics are useful when you want an immediate snapshot of the current list, but having them LIFO as opposed to FIFO means code using this interface copies into a vector and calls `std::reverse` afterwards. We can skip all that if we include a `sweepOnce` method to the AtomicLinkedList.

Reviewed By: yfeldblum

Differential Revision: D63800706

fbshipit-source-id: da872ac23c599358c4e90dcdf267b2ba1b872ce3
  • Loading branch information
Jeffrey Mickey authored and facebook-github-bot committed Oct 24, 2024
1 parent 2aa85fc commit 74b9fee
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
17 changes: 17 additions & 0 deletions folly/AtomicLinkedList.h
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,23 @@ class AtomicLinkedList {
});
}

/**
* Sweeps the list a single time, as a single point in time swap with the
* current contents of the list.
*
* Unlike sweep() it does not loop to ensure the list is empty at some point
* after the last invocation.
*
* Returns false if the list is empty.
*/
template <typename F>
bool sweepOnce(F&& func) {
return list_.sweepOnce([&](Wrapper* wrappedPtr) {
std::unique_ptr<Wrapper> wrapper(wrappedPtr);
func(std::move(wrapper->data));
});
}

/**
* Similar to sweep() but calls func() on elements in LIFO order.
*
Expand Down
23 changes: 23 additions & 0 deletions folly/test/AtomicLinkedListTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,26 @@ TEST(AtomicLinkedList, MoveAssignment) {
EXPECT_TRUE(lastList.empty());
EXPECT_EQ(0, TestObject::numInstances());
}

TEST(AtomicLinkedList, SweepOnce) {
folly::AtomicLinkedList<int> list;
int a(1), b(2), c(3);

list.insertHead(a);
list.insertHead(b);
list.insertHead(c);

size_t id = 1;
list.sweepOnce([&](int&& obj) {
EXPECT_EQ(id, obj);
++id;
});

EXPECT_TRUE(list.empty());

// Test that we can still insert
list.insertHead(a);

EXPECT_FALSE(list.empty());
list.sweepOnce([](int&& obj) { EXPECT_EQ(1, obj); });
}

0 comments on commit 74b9fee

Please sign in to comment.