Commit 8bed0626 authored by Phil Willoughby's avatar Phil Willoughby Committed by Facebook Github Bot 1

Make a SharedPromise from a Future

Summary: Makes it easy to split a Future into multiple Futures

Reviewed By: rongrong

Differential Revision: D3885897

fbshipit-source-id: 6ac9fb22444dd828fbdebb44b06bf3d93d0f7583
parent b16d3a25
......@@ -47,6 +47,11 @@ SharedPromise<T>& SharedPromise<T>::operator=(
return *this;
}
template <class T>
SharedPromise<T>::SharedPromise(Future<T> future) {
future.then(&SharedPromise<T>::setTry, this);
}
template <class T>
size_t SharedPromise<T>::size() {
std::lock_guard<std::mutex> g(mutex_);
......
......@@ -46,6 +46,13 @@ public:
SharedPromise(SharedPromise<T>&&) noexcept;
SharedPromise& operator=(SharedPromise<T>&&) noexcept;
/**
* Provide a way to split a Future<T>. Note that while the Futures from
* `getFuture()' depend on the completion of the parameter Future they do not
* inherit any other properties such as Executor's passed to `via' etc.
*/
explicit SharedPromise(Future<T>);
/**
* Return a Future tied to the shared core state. Unlike Promise::getFuture,
* this can be called an unlimited number of times per SharedPromise.
......
......@@ -125,3 +125,33 @@ TEST(SharedPromise, interruptHandler) {
f.cancel();
EXPECT_TRUE(flag);
}
TEST(SharedPromise, splitFutureSuccess) {
Promise<int> p;
SharedPromise<int> sp(p.getFuture());
auto f1 = sp.getFuture();
EXPECT_FALSE(f1.isReady());
p.setValue(1);
EXPECT_TRUE(f1.isReady());
EXPECT_TRUE(f1.hasValue());
auto f2 = sp.getFuture();
EXPECT_TRUE(f2.isReady());
EXPECT_TRUE(f2.hasValue());
}
TEST(SharedPromise, splitFutureFailure) {
Promise<int> p;
SharedPromise<int> sp(p.getFuture());
auto f1 = sp.getFuture();
EXPECT_FALSE(f1.isReady());
try {
throw std::runtime_error("Oops");
} catch (...) {
p.setException(exception_wrapper(std::current_exception()));
}
EXPECT_TRUE(f1.isReady());
EXPECT_TRUE(f1.hasException());
auto f2 = sp.getFuture();
EXPECT_TRUE(f2.isReady());
EXPECT_TRUE(f2.hasException());
}
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