2 * Copyright 2015-present 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 "folly/experimental/ThreadedRepeatingFunctionRunner.h"
18 #include <folly/system/ThreadName.h>
19 #include <glog/logging.h>
24 ThreadedRepeatingFunctionRunner::ThreadedRepeatingFunctionRunner() {}
26 ThreadedRepeatingFunctionRunner::~ThreadedRepeatingFunctionRunner() {
29 << "ThreadedRepeatingFunctionRunner::stop() should already have been "
30 << "called, since we are now in the Runner's destructor. This is "
31 << "because it means that its threads may be accessing object state "
32 << "that was already destroyed -- e.g. members that were declared "
33 << "after the ThreadedRepeatingFunctionRunner.";
37 void ThreadedRepeatingFunctionRunner::stop() {
41 bool ThreadedRepeatingFunctionRunner::stopImpl() {
43 std::unique_lock<std::mutex> lock(stopMutex_);
45 return false; // Do nothing if stop() is called twice.
50 for (auto& t : threads_) {
56 void ThreadedRepeatingFunctionRunner::add(
59 std::chrono::milliseconds initialSleep) {
60 threads_.emplace_back([
61 name = std::move(name),
67 executeInLoop(std::move(fn), initialSleep);
71 bool ThreadedRepeatingFunctionRunner::waitFor(
72 std::chrono::milliseconds duration) noexcept {
73 using clock = std::chrono::steady_clock;
74 const auto deadline = clock::now() + duration;
75 std::unique_lock<std::mutex> lock(stopMutex_);
77 lock, deadline, [&] { return stopping_ || clock::now() > deadline; });
81 void ThreadedRepeatingFunctionRunner::executeInLoop(
83 std::chrono::milliseconds initialSleep) noexcept {
84 auto duration = initialSleep;
85 while (waitFor(duration)) {