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.
18 #include <folly/fibers/FiberManagerInternal.h>
19 #include <folly/fibers/LoopController.h>
20 #include <folly/io/async/EventBase.h>
21 #include <folly/io/async/VirtualEventBase.h>
32 template <typename EventBaseT>
33 class EventBaseLoopControllerT : public LoopController {
35 explicit EventBaseLoopControllerT();
36 ~EventBaseLoopControllerT();
39 * Attach EventBase after LoopController was created.
41 void attachEventBase(EventBaseT& eventBase);
43 EventBaseT* getEventBase() {
47 void setLoopRunner(InlineFunctionRunner* loopRunner) {
48 loopRunner_ = loopRunner;
52 class ControllerCallback : public folly::EventBase::LoopCallback {
54 explicit ControllerCallback(EventBaseLoopControllerT& controller)
55 : controller_(controller) {}
57 void runLoopCallback() noexcept override {
58 controller_.runLoop();
62 EventBaseLoopControllerT& controller_;
65 class DestructionCallback : public folly::EventBase::LoopCallback {
67 DestructionCallback() : alive_(new int(42)) {}
68 ~DestructionCallback() {
72 void runLoopCallback() noexcept override {
76 std::weak_ptr<void> getWeak() {
82 std::weak_ptr<void> aliveWeak(alive_);
85 while (!aliveWeak.expired()) {
86 // Spin until all operations requiring EventBaseLoopController to be
87 // alive are complete.
91 std::shared_ptr<void> alive_;
94 bool awaitingScheduling_{false};
95 EventBaseT* eventBase_{nullptr};
96 typename EventBaseT::LoopKeepAlive eventBaseKeepAlive_;
97 ControllerCallback callback_;
98 DestructionCallback destructionCallback_;
99 FiberManager* fm_{nullptr};
100 std::atomic<bool> eventBaseAttached_{false};
101 std::weak_ptr<void> aliveWeak_;
102 InlineFunctionRunner* loopRunner_{nullptr};
104 /* LoopController interface */
106 void setFiberManager(FiberManager* fm) override;
107 void schedule() override;
108 void cancel() override;
109 void runLoop() override;
110 void scheduleThreadSafe(std::function<bool()> func) override;
111 void timedSchedule(std::function<void()> func, TimePoint time) override;
113 friend class FiberManager;
116 using EventBaseLoopController = EventBaseLoopControllerT<folly::EventBase>;
120 #include "EventBaseLoopController-inl.h"