(wangle) noexcept move constructor
[folly.git] / folly / wangle / ThreadGate.h
1 /*
2  * Copyright 2014 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 #include <memory>
19 #include "Future.h"
20
21 namespace folly { namespace wangle {
22
23 /**
24   Yo dawg, I heard you like asynchrony so I put asynchrony in your asynchronous
25   framework.
26
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.
30
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.
34
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
37   (the client).
38
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).
44
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.
48
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()>&&)`.
53
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.
58
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
69   using.
70
71   Later (in Later.h) is an alternative mechanism for thread-traversing
72   asynchronous workflows.
73   */
74 class ThreadGate {
75 public:
76   virtual ~ThreadGate() {}
77
78   /**
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
81     (moved).
82
83     There's a lot of nuance in that sentence. Let's break it down.
84
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
90     drives the executor.
91
92     We create the west Promise and return its Future.
93
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.
96
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.
101
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.
106
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. */
110   template <class T>
111   Future<T> gate(std::function<Future<T>()>&& fn) {
112     Promise<T> pWest;
113     Future<T> fWest = pWest.getFuture();
114
115     gate(std::move(fn), std::move(pWest));
116     return fWest;
117   }
118
119   /**
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.
122    *
123    *  Promise<T> pWest;
124    *  Future<T> fWest = pWest.getFuture();
125    *
126    *  // Set up callbacks for west from a thread that is not west.
127    *  fWest.then(...).then(...);
128    *
129    *  threadGate.gate(..., std::move(pWest));
130    *
131    * This function assumes that it is safe to call addEast from a thread that is
132    * not the west thread.
133    */
134   template <class T>
135   void gate(std::function<Future<T>()>&& fn,
136             Promise<T>&& p) {
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));
144         });
145       });
146     });
147   }
148
149   /**
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.
153
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.
157
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
161     of waitFor.)
162
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
165     DummyWaiter.
166     */
167   template <class T>
168   void waitFor(Future<T> const& f) {
169     while (!f.isReady()) {
170       this->makeProgress();
171     }
172   }
173
174   template <class T>
175   typename std::add_lvalue_reference<T>::type
176   value(Future<T>& f) {
177     waitFor<T>(f);
178     return f.value();
179   }
180
181   template <class T>
182   typename std::add_lvalue_reference<const T>::type
183   value(Future<T> const& f) {
184     waitFor<T>(f);
185     return f.value();
186   }
187
188   virtual void addEast(std::function<void()>&&) = 0;
189   virtual void addWest(std::function<void()>&&) = 0;
190   virtual void makeProgress();
191 };
192
193 }} // namespace