blob: 354c308bc1f5a3267c8fecfff8b28ef956f4fbaf [file] [log] [blame]
Florian Mayerc7255fd2018-01-25 10:29:24 +00001/*
2 * Copyright (C) 2018 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 TEST_TASK_RUNNER_THREAD_H_
18#define TEST_TASK_RUNNER_THREAD_H_
19
20#include <condition_variable>
21#include <mutex>
22#include <thread>
23
24#include "perfetto/base/task_runner.h"
25#include "src/base/test/test_task_runner.h"
26
27namespace perfetto {
28
29// Used to perform initialization work on a background TaskRunnerThread.
30class ThreadDelegate {
31 public:
Primiano Tucci3cbb10a2018-04-10 17:52:40 +010032 virtual ~ThreadDelegate();
Florian Mayerc7255fd2018-01-25 10:29:24 +000033
34 // Invoked on the target thread before the message loop is started.
35 virtual void Initialize(base::TaskRunner* task_runner) = 0;
36};
37
38// Background thread which spins a task runner until completed or the thread is
39// destroyed. If the thread is destroyed before the task runner completes, the
40// task runner is quit and the thread is joined.
41class TaskRunnerThread {
42 public:
Lalit Magantibfc3d3e2018-03-22 20:28:38 +000043 explicit TaskRunnerThread(const char* name);
Florian Mayerc7255fd2018-01-25 10:29:24 +000044 ~TaskRunnerThread();
45
46 // Blocks until the thread has been created and Initialize() has been
47 // called.
48 void Start(std::unique_ptr<ThreadDelegate> delegate);
49
Lalit Magantibfc3d3e2018-03-22 20:28:38 +000050 // Blocks until the thread has been stopped and joined.
51 void Stop();
52
53 uint64_t GetThreadCPUTimeNs();
54
Florian Mayerc7255fd2018-01-25 10:29:24 +000055 private:
56 void Run(std::unique_ptr<ThreadDelegate> delegate);
57
Lalit Magantibfc3d3e2018-03-22 20:28:38 +000058 const char* const name_;
Florian Mayerc7255fd2018-01-25 10:29:24 +000059 std::thread thread_;
60 std::condition_variable ready_;
61
62 // All variables below this point are protected by |mutex_|.
63 std::mutex mutex_;
Primiano Tucciec62e3e2019-07-26 22:18:31 +010064 base::UnixTaskRunner* runner_ = nullptr;
Florian Mayerc7255fd2018-01-25 10:29:24 +000065};
66
67} // namespace perfetto
68
Lalit Maganti503f6c42018-02-16 17:36:13 +000069#endif // TEST_TASK_RUNNER_THREAD_H_