1 /* 2 * Copyright (C) 2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #include "thread_pool.h" 17 #include "iostream" 18 #include <string> 19 20 namespace OHOS::SmartPerf { ThreadPool(size_t threadNum)21ThreadPool::ThreadPool(size_t threadNum) 22 { 23 ths_.reserve(threadNum); 24 for (size_t i = 0; i < threadNum; ++i) { 25 ths_.emplace_back(std::thread(&ThreadPool::Run, this)); 26 } 27 } 28 ~ThreadPool()29ThreadPool::~ThreadPool() 30 { 31 stop_.store(true); 32 cond_.notify_all(); 33 for (auto& item : ths_) { 34 if (item.joinable()) { 35 item.join(); 36 } 37 } 38 } 39 Stop()40void ThreadPool::Stop() 41 { 42 stop_.store(true); 43 cond_.notify_all(); 44 for (auto& item : ths_) { 45 if (item.joinable()) { 46 item.join(); 47 } 48 } 49 } 50 Run()51void ThreadPool::Run() 52 { 53 while (!stop_) { 54 std::function<void()> task = nullptr; 55 { 56 std::unique_lock<std::mutex> lock(mtx_); 57 cond_.wait(lock, [this] { return stop_ || !this->tasks_.empty(); }); 58 if (stop_ || tasks_.empty()) { 59 return; 60 } 61 task = std::move(tasks_.front()); 62 tasks_.pop(); 63 } 64 if (task != nullptr) { 65 task(); 66 } 67 } 68 } 69 }