2 * Copyright 2017 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/VirtualEventBase.h>
27 class EventBaseLoopController : public LoopController {
29 explicit EventBaseLoopController();
30 ~EventBaseLoopController() override;
33 * Attach EventBase after LoopController was created.
35 void attachEventBase(EventBase& eventBase);
36 void attachEventBase(VirtualEventBase& eventBase);
38 VirtualEventBase* getEventBase() {
42 void setLoopRunner(InlineFunctionRunner* loopRunner) {
43 loopRunner_ = loopRunner;
47 class ControllerCallback : public folly::EventBase::LoopCallback {
49 explicit ControllerCallback(EventBaseLoopController& controller)
50 : controller_(controller) {}
52 void runLoopCallback() noexcept override {
53 controller_.runLoop();
57 EventBaseLoopController& controller_;
60 class DestructionCallback : public folly::EventBase::LoopCallback {
62 DestructionCallback() : alive_(new int(42)) {}
63 ~DestructionCallback() override {
67 void runLoopCallback() noexcept override {
71 std::weak_ptr<void> getWeak() {
77 std::weak_ptr<void> aliveWeak(alive_);
80 while (!aliveWeak.expired()) {
81 // Spin until all operations requiring EventBaseLoopController to be
82 // alive are complete.
86 std::shared_ptr<void> alive_;
89 bool awaitingScheduling_{false};
90 VirtualEventBase* eventBase_{nullptr};
91 Executor::KeepAlive eventBaseKeepAlive_;
92 ControllerCallback callback_;
93 DestructionCallback destructionCallback_;
94 FiberManager* fm_{nullptr};
95 std::atomic<bool> eventBaseAttached_{false};
96 std::weak_ptr<void> aliveWeak_;
97 InlineFunctionRunner* loopRunner_{nullptr};
99 /* LoopController interface */
101 void setFiberManager(FiberManager* fm) override;
102 void schedule() override;
103 void cancel() override;
104 void runLoop() override;
105 void scheduleThreadSafe(std::function<bool()> func) override;
106 void timedSchedule(std::function<void()> func, TimePoint time) override;
108 friend class FiberManager;
114 #include "EventBaseLoopController-inl.h"