2 * Copyright 2016 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 Future<T> SharedPromise<T>::getFuture() {
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().getFuture();
73 typename std::enable_if<std::is_base_of<std::exception, E>::value>::type
74 SharedPromise<T>::setException(E const& e) {
79 void SharedPromise<T>::setException(std::exception_ptr const& ep) {
84 void SharedPromise<T>::setException(exception_wrapper ew) {
85 setTry(Try<T>(std::move(ew)));
89 void SharedPromise<T>::setInterruptHandler(
90 std::function<void(exception_wrapper const&)> fn) {
91 std::lock_guard<std::mutex> g(mutex_);
95 interruptHandler_ = fn;
96 for (auto& p : promises_) {
97 p.setInterruptHandler(fn);
103 void SharedPromise<T>::setValue(M&& v) {
104 setTry(Try<T>(std::forward<M>(v)));
109 void SharedPromise<T>::setWith(F&& func) {
110 setTry(makeTryWith(std::forward<F>(func)));
114 void SharedPromise<T>::setTry(Try<T>&& t) {
115 std::vector<Promise<T>> promises;
118 std::lock_guard<std::mutex> g(mutex_);
120 throw PromiseAlreadySatisfied();
124 promises.swap(promises_);
127 for (auto& p : promises) {
128 p.setTry(Try<T>(try_));
133 bool SharedPromise<T>::isFulfilled() {