1 /* 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 27 namespace perfetto { 28 29 // Used to perform initialization work on a background TaskRunnerThread. 30 class ThreadDelegate { 31 public: 32 virtual ~ThreadDelegate(); 33 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. 41 class TaskRunnerThread { 42 public: 43 explicit TaskRunnerThread(const char* name); 44 ~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 50 // Blocks until the thread has been stopped and joined. 51 void Stop(); 52 53 uint64_t GetThreadCPUTimeNs(); 54 55 private: 56 void Run(std::unique_ptr<ThreadDelegate> delegate); 57 58 const char* const name_; 59 std::thread thread_; 60 std::condition_variable ready_; 61 62 // All variables below this point are protected by |mutex_|. 63 std::mutex mutex_; 64 base::PlatformTaskRunner* runner_ = nullptr; 65 }; 66 67 } // namespace perfetto 68 69 #endif // TEST_TASK_RUNNER_THREAD_H_ 70