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.
18 #include <folly/Likely.h>
20 #include <folly/experimental/fibers/LoopController.h>
22 namespace folly { namespace fibers {
26 class SimpleLoopController : public LoopController {
28 SimpleLoopController()
30 stopRequested_(false) {
34 * Run FiberManager loop; if no ready task are present,
35 * run provided function. Stops after both stop() has been called
36 * and no waiting tasks remain.
41 stopRequested_ = false;
43 while (LIKELY(waiting || !stopRequested_)) {
46 auto time = Clock::now();
48 for (size_t i=0; i<scheduledFuncs_.size(); ++i) {
49 if (scheduledFuncs_[i].first <= time) {
50 scheduledFuncs_[i].second();
51 swap(scheduledFuncs_[i], scheduledFuncs_.back());
52 scheduledFuncs_.pop_back();
59 waiting = fm_->loopUntilNoReady();
65 * Requests exit from loop() as soon as all waiting tasks complete.
68 stopRequested_ = true;
71 int remoteScheduleCalled() const {
72 return remoteScheduleCalled_;
75 void schedule() override {
79 void timedSchedule(std::function<void()> func, TimePoint time) override {
80 scheduledFuncs_.emplace_back(time, std::move(func));
85 std::atomic<bool> scheduled_{false};
87 std::atomic<int> remoteScheduleCalled_{0};
88 std::vector<std::pair<TimePoint, std::function<void()>>> scheduledFuncs_;
90 /* LoopController interface */
92 void setFiberManager(FiberManager* fm) override {
96 void cancel() override {
100 void scheduleThreadSafe() override {
101 ++remoteScheduleCalled_;
105 friend class FiberManager;