2 * Copyright 2014 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "ManualExecutor.h"
25 namespace folly { namespace wangle {
27 ManualExecutor::ManualExecutor() {
28 if (sem_init(&sem_, 0, 0) == -1) {
29 throw std::runtime_error(std::string("sem_init: ") + strerror(errno));
33 void ManualExecutor::add(std::function<void()>&& callback) {
34 std::lock_guard<std::mutex> lock(lock_);
35 actions_.push(callback);
39 size_t ManualExecutor::run() {
45 std::lock_guard<std::mutex> lock(lock_);
47 while (!scheduledActions_.empty()) {
48 auto& sa = scheduledActions_.top();
51 actions_.push(sa.action);
52 scheduledActions_.pop();
58 for (count = 0; count < n; count++) {
60 std::lock_guard<std::mutex> lock(lock_);
61 if (actions_.empty()) {
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.
70 action = std::move(actions_.front());
79 void ManualExecutor::wait() {
82 std::lock_guard<std::mutex> lock(lock_);
83 if (!actions_.empty())
87 auto ret = sem_wait(&sem_);
91 if (errno != EINVAL) {
92 throw std::runtime_error(std::string("sem_wait: ") + strerror(errno));