0f2dced9ce40e8be147296aa6228a61e2d78aa7f
[folly.git] / folly / experimental / fibers / TimeoutController.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 #pragma once
17
18 #include <chrono>
19 #include <functional>
20 #include <memory>
21 #include <queue>
22
23 #include <boost/intrusive/list.hpp>
24
25 #include <folly/Likely.h>
26
27 #include <folly/experimental/fibers/LoopController.h>
28
29 namespace folly {
30 namespace fibers {
31
32 class TimeoutController
33     : public std::enable_shared_from_this<TimeoutController> {
34  public:
35   typedef std::chrono::steady_clock Clock;
36   typedef std::chrono::time_point<Clock> TimePoint;
37   typedef Clock::duration Duration;
38
39   explicit TimeoutController(LoopController& loopController);
40
41   intptr_t registerTimeout(std::function<void()> f, Duration duration);
42   void cancel(intptr_t id);
43
44   void runTimeouts(TimePoint time);
45
46  private:
47   void scheduleRun();
48
49   struct TimeoutHandle;
50   typedef std::queue<TimeoutHandle> TimeoutHandleList;
51   typedef std::unique_ptr<TimeoutHandleList> TimeoutHandleListPtr;
52
53   struct TimeoutHandle {
54     TimeoutHandle(
55         std::function<void()> func_,
56         TimePoint timeout_,
57         TimeoutHandleList& list_)
58         : func(std::move(func_)), timeout(timeout_), list(list_) {}
59
60     std::function<void()> func;
61     bool canceled{false};
62     TimePoint timeout;
63     TimeoutHandleList& list;
64   };
65
66   std::vector<std::pair<Duration, TimeoutHandleListPtr>> timeoutHandleBuckets_;
67   TimePoint nextTimeout_;
68   LoopController& loopController_;
69 };
70 }
71 }