2017
[folly.git] / folly / futures / SharedPromise.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #pragma once
18
19 #include <folly/futures/Promise.h>
20 #include <folly/Portability.h>
21
22 namespace folly {
23
24 /*
25  * SharedPromise provides the same interface as Promise, but you can extract
26  * multiple Futures from it, i.e. you can call getFuture() as many times as
27  * you'd like. When the SharedPromise is fulfilled, all of the Futures will be
28  * called back. Calls to getFuture() after the SharedPromise is fulfilled return
29  * a completed Future. If you find yourself constructing collections of Promises
30  * and fulfilling them simultaneously with the same value, consider this
31  * utility instead. Likewise, if you find yourself in need of setting multiple
32  * callbacks on the same Future (which is indefinitely unsupported), consider
33  * refactoring to use SharedPromise to "split" the Future.
34  */
35 template <class T>
36 class SharedPromise {
37 public:
38   SharedPromise() = default;
39   ~SharedPromise() = default;
40
41   // not copyable
42   SharedPromise(SharedPromise const&) = delete;
43   SharedPromise& operator=(SharedPromise const&) = delete;
44
45   // movable
46   SharedPromise(SharedPromise<T>&&) noexcept;
47   SharedPromise& operator=(SharedPromise<T>&&) noexcept;
48
49   /**
50    * Provide a way to split a Future<T>. Note that while the Futures from
51    * `getFuture()' depend on the completion of the parameter Future they do not
52    * inherit any other properties such as Executor's passed to `via' etc.
53    */
54   explicit SharedPromise(Future<T>);
55
56   /**
57    * Return a Future tied to the shared core state. Unlike Promise::getFuture,
58    * this can be called an unlimited number of times per SharedPromise.
59    */
60   Future<T> getFuture();
61
62   /** Return the number of Futures associated with this SharedPromise */
63   size_t size();
64
65   /** Fulfill the SharedPromise with an exception_wrapper */
66   void setException(exception_wrapper ew);
67
68   /** Fulfill the SharedPromise with an exception_ptr, e.g.
69     try {
70       ...
71     } catch (...) {
72       p.setException(std::current_exception());
73     }
74     */
75   FOLLY_DEPRECATED("use setException(exception_wrapper)")
76   void setException(std::exception_ptr const&);
77
78   /** Fulfill the SharedPromise with an exception type E, which can be passed to
79     std::make_exception_ptr(). Useful for originating exceptions. If you
80     caught an exception the exception_wrapper form is more appropriate.
81     */
82   template <class E>
83   typename std::enable_if<std::is_base_of<std::exception, E>::value>::type
84   setException(E const&);
85
86   /// Set an interrupt handler to handle interrupts. See the documentation for
87   /// Future::raise(). Your handler can do whatever it wants, but if you
88   /// bother to set one then you probably will want to fulfill the SharedPromise with
89   /// an exception (or special value) indicating how the interrupt was
90   /// handled.
91   void setInterruptHandler(std::function<void(exception_wrapper const&)>);
92
93   /// Sugar to fulfill this SharedPromise<Unit>
94   template <class B = T>
95   typename std::enable_if<std::is_same<Unit, B>::value, void>::type
96   setValue() {
97     setTry(Try<T>(T()));
98   }
99
100   /** Set the value (use perfect forwarding for both move and copy) */
101   template <class M>
102   void setValue(M&& value);
103
104   void setTry(Try<T>&& t);
105
106   /** Fulfill this SharedPromise with the result of a function that takes no
107     arguments and returns something implicitly convertible to T.
108     Captures exceptions. e.g.
109
110     p.setWith([] { do something that may throw; return a T; });
111   */
112   template <class F>
113   void setWith(F&& func);
114
115   bool isFulfilled();
116
117 private:
118   std::mutex mutex_;
119   size_t size_{0};
120   bool hasValue_{false};
121   Try<T> try_;
122   std::vector<Promise<T>> promises_;
123   std::function<void(exception_wrapper const&)> interruptHandler_;
124 };
125
126 }
127
128 #include <folly/futures/Future.h>
129 #include <folly/futures/SharedPromise-inl.h>