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/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();
57 waiting = fm_->loopUntilNoReady();
63 * Requests exit from loop() as soon as all waiting tasks complete.
66 stopRequested_ = true;
69 int remoteScheduleCalled() const {
70 return remoteScheduleCalled_;
73 void schedule() override {
77 void timedSchedule(std::function<void()> func, TimePoint time) override {
78 scheduledFuncs_.emplace_back(time, std::move(func));
83 std::atomic<bool> scheduled_{false};
85 std::atomic<int> remoteScheduleCalled_{0};
86 std::vector<std::pair<TimePoint, std::function<void()>>> scheduledFuncs_;
88 /* LoopController interface */
90 void setFiberManager(FiberManager* fm) override {
94 void cancel() override {
98 void scheduleThreadSafe(std::function<bool()> func) override {
100 ++remoteScheduleCalled_;
105 friend class FiberManager;