global executors with weak_ptr semantics
[folly.git] / folly / Executor.h
1 /*
2  * Copyright 2014 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 <functional>
21
22 namespace folly {
23
24 typedef std::function<void()> Func;
25
26 /// An Executor accepts units of work with add(), which should be
27 /// threadsafe.
28 class Executor {
29  public:
30   virtual ~Executor() = default;
31
32   /// Enqueue a function to executed by this executor. This and all
33   /// variants must be threadsafe.
34   virtual void add(Func) = 0;
35
36   /// A convenience function for shared_ptr to legacy functors.
37   ///
38   /// Sometimes you have a functor that is move-only, and therefore can't be
39   /// converted to a std::function (e.g. std::packaged_task). In that case,
40   /// wrap it in a shared_ptr (or maybe folly::MoveWrapper) and use this.
41   template <class P>
42   void addPtr(P fn) {
43     this->add([fn]() mutable { (*fn)(); });
44   }
45 };
46
47 } // folly