2 * Copyright 2017 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
22 SharedPromise<T>::SharedPromise(SharedPromise<T>&& other) noexcept {
23 *this = std::move(other);
27 SharedPromise<T>& SharedPromise<T>::operator=(
28 SharedPromise<T>&& other) noexcept {
33 // std::lock will perform deadlock avoidance, in case
34 // Thread A: p1 = std::move(p2)
35 // Thread B: p2 = std::move(p1)
37 std::lock(mutex_, other.mutex_);
38 std::lock_guard<std::mutex> g1(mutex_, std::adopt_lock);
39 std::lock_guard<std::mutex> g2(other.mutex_, std::adopt_lock);
41 std::swap(size_, other.size_);
42 std::swap(hasValue_, other.hasValue_);
43 std::swap(try_, other.try_);
44 std::swap(interruptHandler_, other.interruptHandler_);
45 std::swap(promises_, other.promises_);
51 size_t SharedPromise<T>::size() {
52 std::lock_guard<std::mutex> g(mutex_);
57 SemiFuture<T> SharedPromise<T>::getSemiFuture() {
58 std::lock_guard<std::mutex> g(mutex_);
61 return makeFuture<T>(Try<T>(try_));
63 promises_.emplace_back();
64 if (interruptHandler_) {
65 promises_.back().setInterruptHandler(interruptHandler_);
67 return promises_.back().getSemiFuture();
72 Future<T> SharedPromise<T>::getFuture() {
73 return getSemiFuture().via(&folly::InlineExecutor::instance());
78 typename std::enable_if<std::is_base_of<std::exception, E>::value>::type
79 SharedPromise<T>::setException(E const& e) {
84 void SharedPromise<T>::setException(std::exception_ptr const& ep) {
89 void SharedPromise<T>::setException(exception_wrapper ew) {
90 setTry(Try<T>(std::move(ew)));
94 void SharedPromise<T>::setInterruptHandler(
95 std::function<void(exception_wrapper const&)> fn) {
96 std::lock_guard<std::mutex> g(mutex_);
100 interruptHandler_ = fn;
101 for (auto& p : promises_) {
102 p.setInterruptHandler(fn);
108 void SharedPromise<T>::setValue(M&& v) {
109 setTry(Try<T>(std::forward<M>(v)));
114 void SharedPromise<T>::setWith(F&& func) {
115 setTry(makeTryWith(std::forward<F>(func)));
119 void SharedPromise<T>::setTry(Try<T>&& t) {
120 std::vector<Promise<T>> promises;
123 std::lock_guard<std::mutex> g(mutex_);
125 throwPromiseAlreadySatisfied();
129 promises.swap(promises_);
132 for (auto& p : promises) {
133 p.setTry(Try<T>(try_));
138 bool SharedPromise<T>::isFulfilled() {
139 std::lock_guard<std::mutex> g(mutex_);