folly copyright 2015 -> copyright 2016
[folly.git] / folly / futures / ManualExecutor.cpp
1 /*
2  * Copyright 2016 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 void ManualExecutor::add(Func callback) {
28   std::lock_guard<std::mutex> lock(lock_);
29   funcs_.push(std::move(callback));
30   sem_.post();
31 }
32
33 size_t ManualExecutor::run() {
34   size_t count;
35   size_t n;
36   Func func;
37
38   {
39     std::lock_guard<std::mutex> lock(lock_);
40
41     while (!scheduledFuncs_.empty()) {
42       auto& sf = scheduledFuncs_.top();
43       if (sf.time > now_)
44         break;
45       funcs_.push(sf.func);
46       scheduledFuncs_.pop();
47     }
48
49     n = funcs_.size();
50   }
51
52   for (count = 0; count < n; count++) {
53     {
54       std::lock_guard<std::mutex> lock(lock_);
55       if (funcs_.empty()) {
56         break;
57       }
58
59       // Balance the semaphore so it doesn't grow without bound
60       // if nobody is calling wait().
61       // This may fail (with EAGAIN), that's fine.
62       sem_.tryWait();
63
64       func = std::move(funcs_.front());
65       funcs_.pop();
66     }
67     func();
68   }
69
70   return count;
71 }
72
73 void ManualExecutor::wait() {
74   while (true) {
75     {
76       std::lock_guard<std::mutex> lock(lock_);
77       if (!funcs_.empty())
78         break;
79     }
80
81     sem_.wait();
82   }
83 }
84
85 void ManualExecutor::advanceTo(TimePoint const& t) {
86   if (t > now_) {
87     now_ = t;
88   }
89   run();
90 }
91
92 } // folly