Copyright 2014->2015
[folly.git] / folly / futures / ManualExecutor.cpp
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 #include <folly/futures/ManualExecutor.h>
18
19 #include <string.h>
20 #include <string>
21 #include <tuple>
22
23 #include <stdexcept>
24
25 namespace folly {
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(Func callback) {
34   std::lock_guard<std::mutex> lock(lock_);
35   funcs_.push(std::move(callback));
36   sem_post(&sem_);
37 }
38
39 size_t ManualExecutor::run() {
40   size_t count;
41   size_t n;
42   Func func;
43
44   {
45     std::lock_guard<std::mutex> lock(lock_);
46
47     while (!scheduledFuncs_.empty()) {
48       auto& sf = scheduledFuncs_.top();
49       if (sf.time > now_)
50         break;
51       funcs_.push(sf.func);
52       scheduledFuncs_.pop();
53     }
54
55     n = funcs_.size();
56   }
57
58   for (count = 0; count < n; count++) {
59     {
60       std::lock_guard<std::mutex> lock(lock_);
61       if (funcs_.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       func = std::move(funcs_.front());
71       funcs_.pop();
72     }
73     func();
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 (!funcs_.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 } // folly