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/Likely.h>
20 #include <folly/fibers/LoopController.h>
27 class SimpleLoopController : public LoopController {
29 SimpleLoopController() : fm_(nullptr), stopRequested_(false) {}
32 * Run FiberManager loop; if no ready task are present,
33 * run provided function. Stops after both stop() has been called
34 * and no waiting tasks remain.
39 stopRequested_ = false;
41 while (LIKELY(waiting || !stopRequested_)) {
44 auto time = Clock::now();
46 for (size_t i = 0; i < scheduledFuncs_.size(); ++i) {
47 if (scheduledFuncs_[i].first <= time) {
48 scheduledFuncs_[i].second();
49 swap(scheduledFuncs_[i], scheduledFuncs_.back());
50 scheduledFuncs_.pop_back();
58 waiting = fm_->hasTasks();
64 * Requests exit from loop() as soon as all waiting tasks complete.
67 stopRequested_ = true;
70 int remoteScheduleCalled() const {
71 return remoteScheduleCalled_;
74 void runLoop() override {
75 fm_->loopUntilNoReadyImpl();
78 void schedule() override {
82 void timedSchedule(std::function<void()> func, TimePoint time) override {
83 scheduledFuncs_.emplace_back(time, std::move(func));
88 std::atomic<bool> scheduled_{false};
90 std::atomic<int> remoteScheduleCalled_{0};
91 std::vector<std::pair<TimePoint, std::function<void()>>> scheduledFuncs_;
93 /* LoopController interface */
95 void setFiberManager(FiberManager* fm) override {
99 void cancel() override {
103 void scheduleThreadSafe(std::function<bool()> func) override {
105 ++remoteScheduleCalled_;
110 friend class FiberManager;