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