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.
23 #include <unordered_set>
26 #include <folly/AtomicLinkedList.h>
27 #include <folly/Executor.h>
28 #include <folly/Likely.h>
29 #include <folly/IntrusiveList.h>
30 #include <folly/futures/Try.h>
32 #include <folly/experimental/fibers/BoostContextCompatibility.h>
33 #include <folly/experimental/fibers/ExecutionObserver.h>
34 #include <folly/experimental/fibers/Fiber.h>
35 #include <folly/experimental/fibers/traits.h>
37 #ifdef USE_GUARD_ALLOCATOR
38 #include <folly/experimental/fibers/GuardPageAllocator.h>
41 namespace folly { namespace fibers {
46 class TimeoutController;
54 * @brief Single-threaded task execution engine.
56 * FiberManager allows semi-parallel task execution on the same thread. Each
57 * task can notify FiberManager that it is blocked on something (via await())
58 * call. This will pause execution of this task and it will be resumed only
59 * when it is unblocked (via setData()).
61 class FiberManager : public ::folly::Executor {
64 static constexpr size_t kDefaultStackSize{16 * 1024};
67 * Maximum stack size for fibers which will be used for executing all the
70 size_t stackSize{kDefaultStackSize};
73 * Record exact amount of stack used.
75 * This is fairly expensive: we fill each newly allocated stack
76 * with some known value and find the boundary of unused stack
77 * with linear search every time we surrender the stack back to fibersPool.
78 * 0 disables stack recording.
80 size_t recordStackEvery{0};
83 * Keep at most this many free fibers in the pool.
84 * This way the total number of fibers in the system is always bounded
85 * by the number of active fibers + maxFibersPoolSize.
87 size_t maxFibersPoolSize{1000};
89 constexpr Options() {}
92 typedef std::function<void(std::exception_ptr, std::string)>
95 FiberManager(const FiberManager&) = delete;
96 FiberManager& operator=(const FiberManager&) = delete;
99 * Initializes, but doesn't start FiberManager loop
101 * @param loopController
102 * @param options FiberManager options
104 explicit FiberManager(std::unique_ptr<LoopController> loopController,
105 Options options = Options());
108 * Initializes, but doesn't start FiberManager loop
110 * @param loopController
111 * @param options FiberManager options
112 * @tparam LocalT only local of this type may be stored on fibers.
113 * Locals of other types will be considered thread-locals.
115 template <typename LocalT>
116 FiberManager(LocalType<LocalT>,
117 std::unique_ptr<LoopController> loopController,
118 Options options = Options());
126 LoopController& loopController();
127 const LoopController& loopController() const;
130 * Keeps running ready tasks until the list of ready tasks is empty.
132 * @return True if there are any waiting tasks remaining.
134 bool loopUntilNoReady();
137 * @return true if there are outstanding tasks.
139 bool hasTasks() const;
142 * Sets exception callback which will be called if any of the tasks throws an
147 void setExceptionCallback(ExceptionCallback ec);
150 * Add a new task to be executed. Must be called from FiberManager's thread.
152 * @param func Task functor; must have a signature of `void func()`.
153 * The object will be destroyed once task execution is complete.
155 template <typename F>
156 void addTask(F&& func);
159 * Add a new task to be executed. Safe to call from other threads.
161 * @param func Task function; must have a signature of `void func()`.
162 * The object will be destroyed once task execution is complete.
164 template <typename F>
165 void addTaskRemote(F&& func);
167 // Executor interface calls addTaskRemote
168 void add(std::function<void()> f) {
169 addTaskRemote(std::move(f));
173 * Add a new task. When the task is complete, execute finally(Try<Result>&&)
174 * on the main context.
176 * @param func Task functor; must have a signature of `T func()` for some T.
177 * @param finally Finally functor; must have a signature of
178 * `void finally(Try<T>&&)` and will be passed
179 * the result of func() (including the exception if occurred).
181 template <typename F, typename G>
182 void addTaskFinally(F&& func, G&& finally);
185 * If called from a fiber, immediately switches to the FiberManager's context
186 * and runs func(), going back to the Fiber's context after completion.
187 * Outside a fiber, just calls func() directly.
189 * @return value returned by func().
191 template <typename F>
192 typename std::result_of<F()>::type
193 runInMainContext(F&& func);
196 * Returns a refference to a fiber-local context for given Fiber. Should be
197 * always called with the same T for each fiber. Fiber-local context is lazily
198 * default-constructed on first request.
199 * When new task is scheduled via addTask / addTaskRemote from a fiber its
200 * fiber-local context is copied into the new fiber.
202 template <typename T>
205 template <typename T>
206 static T& localThread();
209 * @return How many fiber objects (and stacks) has this manager allocated.
211 size_t fibersAllocated() const;
214 * @return How many of the allocated fiber objects are currently
217 size_t fibersPoolSize() const;
220 * return true if running activeFiber_ is not nullptr.
222 bool hasActiveFiber() const;
225 * @return What was the most observed fiber stack usage (in bytes).
227 size_t stackHighWatermark() const;
230 * Yield execution of the currently running fiber. Must only be called from a
231 * fiber executing on this FiberManager. The calling fiber will be scheduled
232 * when all other fibers have had a chance to run and the event loop is
238 * Setup fibers execution observation/instrumentation. Fiber locals are
239 * available to observer.
241 * @param observer Fiber's execution observer.
243 void setObserver(ExecutionObserver* observer);
245 static FiberManager& getFiberManager();
246 static FiberManager* getFiberManagerUnsafe();
251 template <typename F>
252 struct AddTaskHelper;
253 template <typename F, typename G>
254 struct AddTaskFinallyHelper;
257 template <typename F>
258 explicit RemoteTask(F&& f) : func(std::forward<F>(f)) {}
259 template <typename F>
260 RemoteTask(F&& f, const Fiber::LocalData& localData_) :
261 func(std::forward<F>(f)),
262 localData(folly::make_unique<Fiber::LocalData>(localData_)) {}
263 std::function<void()> func;
264 std::unique_ptr<Fiber::LocalData> localData;
265 AtomicLinkedListHook<RemoteTask> nextRemoteTask;
268 typedef folly::IntrusiveList<Fiber, &Fiber::listHook_> FiberTailQueue;
270 Fiber* activeFiber_{nullptr}; /**< active fiber, nullptr on main context */
272 * Same as active fiber, but also set for functions run from fiber on main
275 Fiber* currentFiber_{nullptr};
277 FiberTailQueue readyFibers_; /**< queue of fibers ready to be executed */
278 FiberTailQueue yieldedFibers_; /**< queue of fibers which have yielded
280 FiberTailQueue fibersPool_; /**< pool of unitialized Fiber objects */
282 size_t fibersAllocated_{0}; /**< total number of fibers allocated */
283 size_t fibersPoolSize_{0}; /**< total number of fibers in the free pool */
284 size_t fibersActive_{0}; /**< number of running or blocked fibers */
285 size_t fiberId_{0}; /**< id of last fiber used */
287 FContext::ContextStruct mainContext_; /**< stores loop function context */
289 std::unique_ptr<LoopController> loopController_;
290 bool isLoopScheduled_{false}; /**< was the ready loop scheduled to run? */
293 * When we are inside FiberManager loop this points to FiberManager. Otherwise
296 static __thread FiberManager* currentFiberManager_;
299 * runInMainContext implementation for non-void functions.
301 template <typename F>
302 typename std::enable_if<
303 !std::is_same<typename std::result_of<F()>::type, void>::value,
304 typename std::result_of<F()>::type>::type
305 runInMainContextHelper(F&& func);
308 * runInMainContext implementation for void functions
310 template <typename F>
311 typename std::enable_if<
312 std::is_same<typename std::result_of<F()>::type, void>::value,
314 runInMainContextHelper(F&& func);
317 * Allocator used to allocate stack for Fibers in the pool.
318 * Allocates stack on the stack of the main context.
320 #ifdef USE_GUARD_ALLOCATOR
321 /* This is too slow for production use; can be fixed
322 if we allocated all stack storage once upfront */
323 GuardPageAllocator stackAllocator_;
325 std::allocator<unsigned char> stackAllocator_;
328 const Options options_; /**< FiberManager options */
331 * Largest observed individual Fiber stack usage in bytes.
333 size_t stackHighWatermark_{0};
336 * Schedules a loop with loopController (unless already scheduled before).
338 void ensureLoopScheduled();
341 * @return An initialized Fiber object from the pool
346 * Sets local data for given fiber if all conditions are met.
348 void initLocalData(Fiber& fiber);
351 * Function passed to the await call.
353 std::function<void(Fiber&)> awaitFunc_;
356 * Function passed to the runInMainContext call.
358 std::function<void()> immediateFunc_;
361 * Fiber's execution observer.
363 ExecutionObserver* observer_{nullptr};
365 ExceptionCallback exceptionCallback_; /**< task exception callback */
367 folly::AtomicLinkedList<Fiber, &Fiber::nextRemoteReady_> remoteReadyQueue_;
369 folly::AtomicLinkedList<RemoteTask, &RemoteTask::nextRemoteTask>
372 std::shared_ptr<TimeoutController> timeoutManager_;
375 * Only local of this type will be available for fibers.
377 std::type_index localType_;
379 void runReadyFiber(Fiber* fiber);
380 void remoteReadyInsert(Fiber* fiber);
384 * @return true iff we are running in a fiber's context
386 inline bool onFiber() {
387 auto fm = FiberManager::getFiberManagerUnsafe();
388 return fm ? fm->hasActiveFiber() : false;
392 * Add a new task to be executed.
394 * @param func Task functor; must have a signature of `void func()`.
395 * The object will be destroyed once task execution is complete.
397 template <typename F>
398 inline void addTask(F&& func) {
399 return FiberManager::getFiberManager().addTask(std::forward<F>(func));
403 * Add a new task. When the task is complete, execute finally(Try<Result>&&)
404 * on the main context.
405 * Task functor is run and destroyed on the fiber context.
406 * Finally functor is run and destroyed on the main context.
408 * @param func Task functor; must have a signature of `T func()` for some T.
409 * @param finally Finally functor; must have a signature of
410 * `void finally(Try<T>&&)` and will be passed
411 * the result of func() (including the exception if occurred).
413 template <typename F, typename G>
414 inline void addTaskFinally(F&& func, G&& finally) {
415 return FiberManager::getFiberManager().addTaskFinally(
416 std::forward<F>(func), std::forward<G>(finally));
420 * Blocks task execution until given promise is fulfilled.
422 * Calls function passing in a Promise<T>, which has to be fulfilled.
424 * @return data which was used to fulfill the promise.
426 template <typename F>
427 typename FirstArgOf<F>::type::value_type
428 inline await(F&& func);
431 * If called from a fiber, immediately switches to the FiberManager's context
432 * and runs func(), going back to the Fiber's context after completion.
433 * Outside a fiber, just calls func() directly.
435 * @return value returned by func().
437 template <typename F>
438 typename std::result_of<F()>::type
439 inline runInMainContext(F&& func) {
440 auto fm = FiberManager::getFiberManagerUnsafe();
441 if (UNLIKELY(fm == nullptr)) {
444 return fm->runInMainContext(std::forward<F>(func));
448 * Returns a refference to a fiber-local context for given Fiber. Should be
449 * always called with the same T for each fiber. Fiber-local context is lazily
450 * default-constructed on first request.
451 * When new task is scheduled via addTask / addTaskRemote from a fiber its
452 * fiber-local context is copied into the new fiber.
454 template <typename T>
456 auto fm = FiberManager::getFiberManagerUnsafe();
458 return fm->local<T>();
460 return FiberManager::localThread<T>();
463 inline void yield() {
464 auto fm = FiberManager::getFiberManagerUnsafe();
468 std::this_thread::yield();
474 #include "FiberManager-inl.h"