Copyright 2014->2015
[folly.git] / folly / futures / ManualExecutor.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
17 #pragma once
18 #include <folly/futures/DrivableExecutor.h>
19 #include <folly/futures/ScheduledExecutor.h>
20 #include <semaphore.h>
21 #include <memory>
22 #include <mutex>
23 #include <queue>
24 #include <cstdio>
25
26 namespace folly {
27   /// A ManualExecutor only does work when you turn the crank, by calling
28   /// run() or indirectly with makeProgress() or waitFor().
29   ///
30   /// The clock for a manual executor starts at 0 and advances only when you
31   /// ask it to. i.e. time is also under manual control.
32   ///
33   /// NB No attempt has been made to make anything other than add and schedule
34   /// threadsafe.
35   class ManualExecutor : public DrivableExecutor,
36                          public ScheduledExecutor {
37    public:
38     ManualExecutor();
39
40     void add(Func) override;
41
42     /// Do work. Returns the number of functions that were executed (maybe 0).
43     /// Non-blocking, in the sense that we don't wait for work (we can't
44     /// control whether one of the functions blocks).
45     /// This is stable, it will not chase an ever-increasing tail of work.
46     /// This also means, there may be more work available to perform at the
47     /// moment that this returns.
48     size_t run();
49
50     /// Wait for work to do.
51     void wait();
52
53     /// Wait for work to do, and do it.
54     void makeProgress() {
55       wait();
56       run();
57     }
58
59     /// Implements DrivableExecutor
60     void drive() override {
61       makeProgress();
62     }
63
64     /// makeProgress until this Future is ready.
65     template <class F> void waitFor(F const& f) {
66       // TODO(5427828)
67 #if 0
68       while (!f.isReady())
69         makeProgress();
70 #else
71       while (!f.isReady()) {
72         run();
73       }
74 #endif
75
76     }
77
78     virtual void scheduleAt(Func&& f, TimePoint const& t) override {
79       std::lock_guard<std::mutex> lock(lock_);
80       scheduledFuncs_.emplace(t, std::move(f));
81       sem_post(&sem_);
82     }
83
84     /// Advance the clock. The clock never advances on its own.
85     /// Advancing the clock causes some work to be done, if work is available
86     /// to do (perhaps newly available because of the advanced clock).
87     /// If dur is <= 0 this is a noop.
88     void advance(Duration const& dur) {
89       advanceTo(now_ + dur);
90     }
91
92     /// Advance the clock to this absolute time. If t is <= now(),
93     /// this is a noop.
94     void advanceTo(TimePoint const& t);
95
96     TimePoint now() override { return now_; }
97
98    private:
99     std::mutex lock_;
100     std::queue<Func> funcs_;
101     sem_t sem_;
102
103     // helper class to enable ordering of scheduled events in the priority
104     // queue
105     struct ScheduledFunc {
106       TimePoint time;
107       size_t ordinal;
108       Func func;
109
110       ScheduledFunc(TimePoint const& t, Func&& f)
111         : time(t), func(std::move(f))
112       {
113         static size_t seq = 0;
114         ordinal = seq++;
115       }
116
117       bool operator<(ScheduledFunc const& b) const {
118         if (time == b.time)
119           return ordinal < b.ordinal;
120         return time < b.time;
121       }
122     };
123     std::priority_queue<ScheduledFunc> scheduledFuncs_;
124     TimePoint now_ = now_.min();
125   };
126
127 }