Add TimedDrivableExecutor to folly.
[folly.git] / folly / executors / NotificationQueueExecutor.h
1 /*
2  * Copyright 2016-present 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 #pragma once
17
18 #include <folly/ExceptionString.h>
19 #include <folly/Function.h>
20 #include <folly/executors/DrivableExecutor.h>
21 #include <folly/io/async/NotificationQueue.h>
22
23 namespace folly {
24
25 class NotificationQueueExecutor : public folly::DrivableExecutor {
26  public:
27   using Func = folly::Func;
28
29   void add(Func func) override {
30     queue_.putMessage(std::move(func));
31   }
32
33   int fileno() const {
34     return consumer_.getFd();
35   }
36
37   void drive() noexcept override {
38     Func func;
39     while (queue_.tryConsume(func)) {
40       try {
41         func();
42       } catch (const std::exception& ex) {
43         LOG(ERROR) << "Exception thrown by NotificationQueueExecutor task."
44                    << "Exception message: " << folly::exceptionStr(ex);
45       } catch (...) {
46         LOG(ERROR) << "Unknown Exception thrown "
47                    << "by NotificationQueueExecutor task.";
48       }
49     }
50   }
51
52  private:
53   folly::NotificationQueue<Func> queue_;
54   folly::NotificationQueue<Func>::SimpleConsumer consumer_{queue_};
55 }; // NotificationQueueExecutor
56
57 } // namespace folly