Commit 881088fc authored by Yedidya Feldblum's avatar Yedidya Feldblum Committed by Facebook Github Bot

Synchronized::exchange

Summary:
[Folly] `Synchronized::exchange`, for assigning a new value and returning the old value.

(Note: this ignores all push blocking failures!)

Differential Revision: D6653482

fbshipit-source-id: 68f4bd330bc2cf37bb92aff98b8ce3221334112e
parent 18b6a2dd
......@@ -691,6 +691,15 @@ struct Synchronized : public SynchronizedBase<
swap(datum_, rhs);
}
/**
* Assign another datum and return the original value. Recommended
* because it keeps the mutex held only briefly.
*/
T exchange(T&& rhs) {
swap(rhs);
return std::move(rhs);
}
/**
* Copies datum to a given target.
*/
......
......@@ -98,6 +98,10 @@ TYPED_TEST(SynchronizedTest, InPlaceConstruction) {
testInPlaceConstruction<TypeParam>();
}
TYPED_TEST(SynchronizedTest, Exchange) {
testExchange<TypeParam>();
}
template <class Mutex>
class SynchronizedTimedTest : public testing::Test {};
......
......@@ -877,5 +877,15 @@ template <class Mutex> void testInPlaceConstruction() {
// This won't compile without in_place
folly::Synchronized<NotCopiableNotMovable> a(folly::in_place, 5, "a");
}
template <class Mutex>
void testExchange() {
std::vector<int> input = {1, 2, 3};
folly::Synchronized<std::vector<int>, Mutex> v(input);
std::vector<int> next = {4, 5, 6};
auto prev = v.exchange(std::move(next));
EXPECT_EQ((std::vector<int>{1, 2, 3}), prev);
EXPECT_EQ((std::vector<int>{4, 5, 6}), v.copy());
}
} // namespace sync_tests
} // namespace folly
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment