1 /*
2  * Copyright (C) 2019 The Android Open Source Project
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 #ifndef INCLUDE_PERFETTO_BASE_THREAD_TASK_RUNNER_H_
18 #define INCLUDE_PERFETTO_BASE_THREAD_TASK_RUNNER_H_
19 
20 #include <functional>
21 #include <thread>
22 
23 #include "perfetto/base/unix_task_runner.h"
24 
25 namespace perfetto {
26 namespace base {
27 
28 // A UnixTaskRunner backed by a dedicated task thread. Shuts down the runner and
29 // joins the thread upon destruction. Can be moved to transfer ownership.
30 //
31 // Guarantees that:
32 // * the UnixTaskRunner will be constructed and destructed on the task thread.
33 // * the task thread will live for the lifetime of the UnixTaskRunner.
34 //
35 class ThreadTaskRunner {
36  public:
CreateAndStart()37   static ThreadTaskRunner CreateAndStart() { return ThreadTaskRunner(); }
38 
39   ThreadTaskRunner(const ThreadTaskRunner&) = delete;
40   ThreadTaskRunner& operator=(const ThreadTaskRunner&) = delete;
41 
42   ThreadTaskRunner(ThreadTaskRunner&&) noexcept;
43   ThreadTaskRunner& operator=(ThreadTaskRunner&&);
44   ~ThreadTaskRunner();
45 
46   // Returns a pointer to the UnixTaskRunner, which is valid for the lifetime of
47   // this ThreadTaskRunner object (unless this object is moved-from, in which
48   // case the pointer remains valid for the lifetime of the new owning
49   // ThreadTaskRunner).
50   //
51   // Warning: do not call Quit() on the returned runner pointer, the termination
52   // should be handled exclusively by this class' destructor.
get()53   UnixTaskRunner* get() const { return task_runner_; }
54 
55  private:
56   ThreadTaskRunner();
57   void RunTaskThread(std::function<void(UnixTaskRunner*)> initializer);
58 
59   std::thread thread_;
60   UnixTaskRunner* task_runner_ = nullptr;
61 };
62 
63 }  // namespace base
64 }  // namespace perfetto
65 
66 #endif  // INCLUDE_PERFETTO_BASE_THREAD_TASK_RUNNER_H_
67