use folly::Function<void()> in folly::Executor interface
[folly.git] / folly / Executor.h
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 #pragma once
18
19 #include <atomic>
20 #include <climits>
21 #include <functional>
22 #include <stdexcept>
23
24 #include <folly/Function.h>
25
26 namespace folly {
27
28 using Func = Function<void()>;
29
30 /// An Executor accepts units of work with add(), which should be
31 /// threadsafe.
32 class Executor {
33  public:
34   virtual ~Executor() = default;
35
36   /// Enqueue a function to executed by this executor. This and all
37   /// variants must be threadsafe.
38   virtual void add(Func) = 0;
39
40   /// Enqueue a function with a given priority, where 0 is the medium priority
41   /// This is up to the implementation to enforce
42   virtual void addWithPriority(Func, int8_t /*priority*/) {
43     throw std::runtime_error(
44         "addWithPriority() is not implemented for this Executor");
45   }
46
47   virtual uint8_t getNumPriorities() const {
48     return 1;
49   }
50
51   static const int8_t LO_PRI  = SCHAR_MIN;
52   static const int8_t MID_PRI = 0;
53   static const int8_t HI_PRI  = SCHAR_MAX;
54
55   /// A convenience function for shared_ptr to legacy functors.
56   ///
57   /// Sometimes you have a functor that is move-only, and therefore can't be
58   /// converted to a std::function (e.g. std::packaged_task). In that case,
59   /// wrap it in a shared_ptr (or maybe folly::MoveWrapper) and use this.
60   template <class P>
61   void addPtr(P fn) {
62     this->add([fn]() mutable { (*fn)(); });
63   }
64 };
65
66 } // folly