2 * Copyright 2015 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(promises_, other.promises_);
50 size_t SharedPromise<T>::size() {
51 std::lock_guard<std::mutex> g(mutex_);
56 Future<T> SharedPromise<T>::getFuture() {
57 std::lock_guard<std::mutex> g(mutex_);
60 return makeFuture<T>(Try<T>(try_));
62 promises_.emplace_back();
63 return promises_.back().getFuture();
69 typename std::enable_if<std::is_base_of<std::exception, E>::value>::type
70 SharedPromise<T>::setException(E const& e) {
75 void SharedPromise<T>::setException(std::exception_ptr const& ep) {
80 void SharedPromise<T>::setException(exception_wrapper ew) {
81 setTry(Try<T>(std::move(ew)));
85 void SharedPromise<T>::setInterruptHandler(
86 std::function<void(exception_wrapper const&)> fn) {
87 std::lock_guard<std::mutex> g(mutex_);
91 for (auto& p : promises_) {
92 p.setInterruptHandler(fn);
98 void SharedPromise<T>::setValue(M&& v) {
99 setTry(Try<T>(std::forward<M>(v)));
104 void SharedPromise<T>::setWith(F&& func) {
105 setTry(makeTryWith(std::forward<F>(func)));
109 void SharedPromise<T>::setTry(Try<T>&& t) {
110 std::vector<Promise<T>> promises;
113 std::lock_guard<std::mutex> g(mutex_);
115 throw PromiseAlreadySatisfied();
119 promises.swap(promises_);
122 for (auto& p : promises) {
123 p.setTry(Try<T>(try_));
128 bool SharedPromise<T>::isFulfilled() {