Store filename and provide detailed message on data access assertion failure.
[folly.git] / folly / Executor.h
1 /*
2  * Copyright 2017 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 <climits>
20
21 #include <folly/Function.h>
22
23 namespace folly {
24
25 using Func = Function<void()>;
26
27 /// An Executor accepts units of work with add(), which should be
28 /// threadsafe.
29 class Executor {
30  public:
31   // Workaround for a linkage problem with explicitly defaulted dtor t22914621
32   virtual ~Executor() {}
33
34   /// Enqueue a function to executed by this executor. This and all
35   /// variants must be threadsafe.
36   virtual void add(Func) = 0;
37
38   /// Enqueue a function with a given priority, where 0 is the medium priority
39   /// This is up to the implementation to enforce
40   virtual void addWithPriority(Func, int8_t priority);
41
42   virtual uint8_t getNumPriorities() const {
43     return 1;
44   }
45
46   static const int8_t LO_PRI  = SCHAR_MIN;
47   static const int8_t MID_PRI = 0;
48   static const int8_t HI_PRI  = SCHAR_MAX;
49
50   class KeepAlive {
51    public:
52     KeepAlive() {}
53
54     void reset() {
55       executor_.reset();
56     }
57
58     explicit operator bool() const {
59       return executor_ != nullptr;
60     }
61
62     Executor* get() const {
63       return executor_.get();
64     }
65
66    private:
67     friend class Executor;
68     explicit KeepAlive(folly::Executor* executor) : executor_(executor) {}
69
70     struct Deleter {
71       void operator()(folly::Executor* executor) {
72         executor->keepAliveRelease();
73       }
74     };
75     std::unique_ptr<folly::Executor, Deleter> executor_;
76   };
77
78   /// Returns a keep-alive token which guarantees that Executor will keep
79   /// processing tasks until the token is released.
80   ///
81   /// If executor does not support keep-alive functionality - dummy token will
82   /// be returned.
83   virtual KeepAlive getKeepAliveToken() {
84     return {};
85   }
86
87  protected:
88   virtual void keepAliveAcquire();
89   virtual void keepAliveRelease();
90
91   KeepAlive makeKeepAlive() {
92     return KeepAlive{this};
93   }
94 };
95
96 } // namespace folly