1 /* 2 * Copyright (C) 2024 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 #include "src/bigtrace/orchestrator/resizable_task_pool.h" 18 19 namespace perfetto::bigtrace { 20 ResizableTaskPool(std::function<void (ThreadWithContext *)> fn)21ResizableTaskPool::ResizableTaskPool(std::function<void(ThreadWithContext*)> fn) 22 : fn_(std::move(fn)) {} 23 24 // Resizes the number of threads in the task pool to |new_size| 25 // 26 // This works by performing one of two possible actions: 27 // 1) When the number of threads is reduced, the excess are cancelled and joined 28 // 2) When the number of threads is increased, new threads are created and 29 // started Resize(uint32_t new_size)30void ResizableTaskPool::Resize(uint32_t new_size) { 31 if (size_t old_size = contextual_threads_.size(); new_size < old_size) { 32 for (size_t i = new_size; i < old_size; ++i) { 33 contextual_threads_[i]->Cancel(); 34 } 35 for (size_t i = new_size; i < old_size; ++i) { 36 contextual_threads_[i]->thread.join(); 37 } 38 contextual_threads_.resize(new_size); 39 } else { 40 contextual_threads_.resize(new_size); 41 for (size_t i = old_size; i < new_size; ++i) { 42 contextual_threads_[i] = std::make_unique<ThreadWithContext>(fn_); 43 } 44 } 45 } 46 47 // Joins all threads in the task pool JoinAll()48void ResizableTaskPool::JoinAll() { 49 for (auto& contextual_thread : contextual_threads_) { 50 contextual_thread->thread.join(); 51 } 52 } 53 54 } // namespace perfetto::bigtrace 55