Fix #includes
[folly.git] / folly / wangle / ManualExecutor.cpp
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 #include <folly/wangle/ManualExecutor.h>
18
19 #include <string.h>
20 #include <string>
21 #include <tuple>
22
23 #include <stdexcept>
24
25 namespace folly { namespace wangle {
26
27 ManualExecutor::ManualExecutor() {
28   if (sem_init(&sem_, 0, 0) == -1) {
29     throw std::runtime_error(std::string("sem_init: ") + strerror(errno));
30   }
31 }
32
33 void ManualExecutor::add(std::function<void()>&& callback) {
34   std::lock_guard<std::mutex> lock(lock_);
35   actions_.push(callback);
36   sem_post(&sem_);
37 }
38
39 size_t ManualExecutor::run() {
40   size_t count;
41   size_t n;
42   Action action;
43
44   {
45     std::lock_guard<std::mutex> lock(lock_);
46
47     while (!scheduledActions_.empty()) {
48       auto& sa = scheduledActions_.top();
49       if (sa.time > now_)
50         break;
51       actions_.push(sa.action);
52       scheduledActions_.pop();
53     }
54
55     n = actions_.size();
56   }
57
58   for (count = 0; count < n; count++) {
59     {
60       std::lock_guard<std::mutex> lock(lock_);
61       if (actions_.empty()) {
62         break;
63       }
64
65       // Balance the semaphore so it doesn't grow without bound
66       // if nobody is calling wait().
67       // This may fail (with EAGAIN), that's fine.
68       sem_trywait(&sem_);
69
70       action = std::move(actions_.front());
71       actions_.pop();
72     }
73     action();
74   }
75
76   return count;
77 }
78
79 void ManualExecutor::wait() {
80   while (true) {
81     {
82       std::lock_guard<std::mutex> lock(lock_);
83       if (!actions_.empty())
84         break;
85     }
86
87     auto ret = sem_wait(&sem_);
88     if (ret == 0) {
89       break;
90     }
91     if (errno != EINVAL) {
92       throw std::runtime_error(std::string("sem_wait: ") + strerror(errno));
93     }
94   }
95 }
96
97 void ManualExecutor::advanceTo(TimePoint const& t) {
98   if (t > now_) {
99     now_ = t;
100   }
101   run();
102 }
103
104 }} // namespace