2 * Copyright 2014 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.
21 namespace folly { namespace wangle {
24 Yo dawg, I heard you like asynchrony so I put asynchrony in your asynchronous
27 Wangle's futures and promises are not thread safe. Counterintuitive as this
28 may seem at first, this is very intentional. Making futures and promises
29 threadsafe drastically reduces their performance.
31 On the other hand, an asynchronous framework isn't much use if you can't do
32 asynchronous things in other threads. So we use the ThreadGate strategy to
33 decouple the threads and their futures with a form of message passing.
35 There are two actors, the east thread which does the asynchronous operation
36 (the server) and the west thread that wants the asynchronous operation done
39 The client calls gate<T>(fn), which returns a Future<T>. Practically speaking
40 the returned Future<T> is the same as the Future<T> returned by fn. But
41 there are actually two futures involved - the original Future which will be
42 generated by fn (called the east Future), and the Future actually returned
43 by gate<T>(fn) (called the west Future).
45 These two futures are decoupled, and although the fulfilment of the east
46 Future eventually causes fulfilment of the west Future, those fulfilments
47 happen in their own threads.
49 In order to make and use a ThreadGate, you need to provide a strategy for
50 executing code in the east and west threads. These strategies may be
51 different. The only requirement is a threadsafe method
52 `void add(function<void()>&&)`.
54 In order for your ThreadGate to do anything, you need to drive those
55 executors somehow. An event loop is a natural fit. A thread pool might be
56 made to work. You could use a busy loop to make a very expensive space
57 heater. 0MQ would be pleasant.
59 Another pattern supported by the ThreadGate is the single-thread pattern. In
60 this pattern, non-blocking I/O drives the asynchronous operation, and
61 futures are fulfilled in an event loop callback. In this scenario,
62 ThreadGate is largely superfluous, and the executors would likely just
63 execute code immediately and inline (and therefore not need to be driven, or
64 threadsafe). But a Waiter strategy that makes progress by driving the event
65 loop one iteration would allow for gate-and-wait code which is agnostic to
66 the small detail that everything happens in one thread. It would also make
67 Future change toward a multithreaded architecture easier, as you need only
68 change the components of the ThreadGate which your client code is already
71 Later (in Later.h) is an alternative mechanism for thread-traversing
72 asynchronous workflows.
76 virtual ~ThreadGate() {}
79 Returns a Future that will be fulfilled after the Future that will be
80 returned by fn() has been fulfilled, with the same value or exception
83 There's a lot of nuance in that sentence. Let's break it down.
85 fn kicks off the asynchronous operation (makes the east Promise), and must
86 be executed in the east thread because the east thread is where the east
87 Promise will be fulfilled. Since gate is being called from the west
88 thread, we must gate fn using the east executor. fn is not executed
89 immediately, it is queued up and will be executed by the east thread as it
92 We create the west Promise and return its Future.
94 When the east thread executes its task, fn is called and the resulting
95 Future gets a callback that will gate another task back to the west.
97 Sometime later, the asynchronous operation completes and the east Promise
98 is fulfilled. Then the east Future executes its callback, which adds a
99 task to the west executor that task is to fulfil the west Promise with the
100 same Try<T>, and it will execute in the west thread.
102 At this point, the west Future is still unfulfilled, even though the east
103 Future has been fulfilled and its callback has finished executing. Only
104 when the west executor is driven to execute that task, the west Future
105 will be completed and its callbacks called.
107 In summary, both east and west need to have plans to drive their
108 executors, or nothing will actually happen. When the executors are driven,
109 then everything flows. */
111 Future<T> gate(std::function<Future<T>()>&& fn) {
113 Future<T> fWest = pWest.getFuture();
115 gate(std::move(fn), std::move(pWest));
120 * This version of gate is to support use cases where the calling thread is
121 * not the west thread. Here is an example use case.
124 * Future<T> fWest = pWest.getFuture();
126 * // Set up callbacks for west from a thread that is not west.
127 * fWest.then(...).then(...);
129 * threadGate.gate(..., std::move(pWest));
131 * This function assumes that it is safe to call addEast from a thread that is
132 * not the west thread.
135 void gate(std::function<Future<T>()>&& fn,
137 folly::MoveWrapper<Promise<T>> pWest(std::move(p));
138 folly::MoveWrapper<std::function<Future<T>()>> fnm(std::move(fn));
139 this->addEast([pWest, fnm, this]() mutable {
140 (*fnm)().then([pWest, this](Try<T>&& t) mutable {
141 folly::MoveWrapper<Try<T>> tm(std::move(t));
142 this->addWest([pWest, tm]() mutable {
143 pWest->fulfilTry(std::move(*tm));
150 If your workflow calls for synchronizing with a
151 west Future, then you may call waitFor, but if your west thread is
152 event-driven you will probably not need to call waitFor.
154 In order for waitFor to behave properly, you must ensure that the Waiter's
155 makeProgress method causes some progress to be made on the west thread,
156 i.e. drives the west executor either directly or indirectly.
158 (Naturally, progress needs to be made on the east thread as well. i.e. the
159 east executor is driven, the asynchronous operation happens, and its
160 Promise is fulfilled. It is likely that none of this concerns the consumer
163 This is the only function that uses the Waiter. It is never called
164 internally. Therefore, if you never use waitFor you can safely provide a
168 void waitFor(Future<T> const& f) {
169 while (!f.isReady()) {
170 this->makeProgress();
175 typename std::add_lvalue_reference<T>::type
176 value(Future<T>& f) {
182 typename std::add_lvalue_reference<const T>::type
183 value(Future<T> const& f) {
188 virtual void addEast(std::function<void()>&&) = 0;
189 virtual void addWest(std::function<void()>&&) = 0;
190 virtual void makeProgress();