Add a full drain for folly's ManualExecutor.
[folly.git] / folly / executors / ManualExecutor.cpp
1 /*
2  * Copyright 2017 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 #include <folly/executors/ManualExecutor.h>
18
19 #include <string.h>
20 #include <string>
21 #include <tuple>
22
23 namespace folly {
24
25 void ManualExecutor::add(Func callback) {
26   std::lock_guard<std::mutex> lock(lock_);
27   funcs_.emplace(std::move(callback));
28   sem_.post();
29 }
30
31 size_t ManualExecutor::run() {
32   size_t count;
33   size_t n;
34   Func func;
35
36   {
37     std::lock_guard<std::mutex> lock(lock_);
38
39     while (!scheduledFuncs_.empty()) {
40       auto& sf = scheduledFuncs_.top();
41       if (sf.time > now_) {
42         break;
43       }
44       funcs_.emplace(sf.moveOutFunc());
45       scheduledFuncs_.pop();
46     }
47
48     n = funcs_.size();
49   }
50
51   for (count = 0; count < n; count++) {
52     {
53       std::lock_guard<std::mutex> lock(lock_);
54       if (funcs_.empty()) {
55         break;
56       }
57
58       // Balance the semaphore so it doesn't grow without bound
59       // if nobody is calling wait().
60       // This may fail (with EAGAIN), that's fine.
61       sem_.tryWait();
62
63       func = std::move(funcs_.front());
64       funcs_.pop();
65     }
66     func();
67   }
68
69   return count;
70 }
71
72 size_t ManualExecutor::drain() {
73   size_t tasksRun = 0;
74   size_t tasksForSingleRun = 0;
75   while ((tasksForSingleRun = run()) != 0) {
76     tasksRun += tasksForSingleRun;
77   }
78   return tasksRun;
79 }
80
81 void ManualExecutor::wait() {
82   while (true) {
83     {
84       std::lock_guard<std::mutex> lock(lock_);
85       if (!funcs_.empty()) {
86         break;
87       }
88     }
89
90     sem_.wait();
91   }
92 }
93
94 void ManualExecutor::advanceTo(TimePoint const& t) {
95   if (t > now_) {
96     now_ = t;
97   }
98   run();
99 }
100
101 } // namespace folly