cd3ce25f6a9964c03778aec010421b86b86f8e52
[folly.git] / folly / experimental / fibers / TimeoutController.h
1 /*
2  * Copyright 2015 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 { namespace fibers {
30
31 class TimeoutController :
32       public std::enable_shared_from_this<TimeoutController> {
33  public:
34   typedef std::chrono::steady_clock Clock;
35   typedef std::chrono::time_point<Clock> TimePoint;
36   typedef Clock::duration Duration;
37
38   explicit TimeoutController(LoopController& loopController);
39
40   intptr_t registerTimeout(std::function<void()> f, Duration duration);
41   void cancel(intptr_t id);
42
43   void runTimeouts(TimePoint time);
44
45  private:
46   void scheduleRun();
47
48   struct TimeoutHandle;
49   typedef std::queue<TimeoutHandle> TimeoutHandleList;
50   typedef std::unique_ptr<TimeoutHandleList> TimeoutHandleListPtr;
51
52   struct TimeoutHandle {
53     TimeoutHandle(std::function<void()> func_,
54                   TimePoint timeout_,
55                   TimeoutHandleList& list_) :
56         func(std::move(func_)), timeout(timeout_), list(list_) {}
57
58     std::function<void()> func;
59     bool canceled{false};
60     TimePoint timeout;
61     TimeoutHandleList& list;
62   };
63
64   std::vector<std::pair<Duration, TimeoutHandleListPtr>> timeoutHandleBuckets_;
65   TimePoint nextTimeout_;
66   LoopController& loopController_;
67 };
68
69 }}