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.
16 #include "FiberManager.h"
18 #include <sys/syscall.h>
24 #include <glog/logging.h>
26 #include <folly/experimental/fibers/Fiber.h>
27 #include <folly/experimental/fibers/LoopController.h>
29 namespace folly { namespace fibers {
31 __thread FiberManager* FiberManager::currentFiberManager_ = nullptr;
33 FiberManager::FiberManager(std::unique_ptr<LoopController> loopController,
35 loopController_(std::move(loopController)),
37 exceptionCallback_([](std::exception_ptr e, std::string context) {
39 std::rethrow_exception(e);
40 } catch (const std::exception& e) {
41 LOG(DFATAL) << "Exception " << typeid(e).name()
42 << " with message '" << e.what() << "' was thrown in "
43 << "FiberManager with context '" << context << "'";
46 LOG(DFATAL) << "Unknown exception was thrown in FiberManager with "
47 << "context '" << context << "'";
51 timeoutManager_(std::make_shared<TimeoutController>(*loopController_)) {
52 loopController_->setFiberManager(this);
55 FiberManager::~FiberManager() {
56 if (isLoopScheduled_) {
57 loopController_->cancel();
62 while (!fibersPool_.empty()) {
63 fibersPool_.pop_front_and_dispose([] (Fiber* fiber) {
67 assert(readyFibers_.empty());
68 assert(fibersActive_ == 0);
71 LoopController& FiberManager::loopController() {
72 return *loopController_;
75 const LoopController& FiberManager::loopController() const {
76 return *loopController_;
79 bool FiberManager::hasTasks() const {
80 return fibersActive_ > 0 ||
81 !remoteReadyQueue_.empty() ||
82 !remoteTaskQueue_.empty();
85 Fiber* FiberManager::getFiber() {
86 Fiber* fiber = nullptr;
87 if (fibersPool_.empty()) {
88 fiber = new Fiber(*this);
91 fiber = &fibersPool_.front();
92 fibersPool_.pop_front();
93 assert(fibersPoolSize_ > 0);
99 bool recordStack = (options_.recordStackEvery != 0) &&
100 (fiberId_ % options_.recordStackEvery == 0);
101 fiber->init(recordStack);
105 void FiberManager::setExceptionCallback(FiberManager::ExceptionCallback ec) {
107 exceptionCallback_ = std::move(ec);
110 size_t FiberManager::fibersAllocated() const {
111 return fibersAllocated_;
114 size_t FiberManager::fibersPoolSize() const {
115 return fibersPoolSize_;
118 size_t FiberManager::stackHighWatermark() const {
119 return stackHighWatermark_;
122 void FiberManager::remoteReadyInsert(Fiber* fiber) {
123 if (remoteReadyQueue_.insertHead(fiber)) {
124 loopController_->scheduleThreadSafe();