• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef THREAD_POOL_H
17 #define THREAD_POOL_H
18 
19 #include <atomic>
20 #include <functional>
21 #include <future>
22 #include <queue>
23 #include <stdexcept>
24 #include <thread>
25 
26 namespace OHOS::SmartPerf {
27 class ThreadPool {
28 public:
29     ThreadPool() = delete;
30     explicit ThreadPool(size_t);
31 
32     template <class FUN, class... ARGS>
PushTask(FUN && f,ARGS &&...args)33     std::future<typename std::invoke_result<FUN, ARGS...>::type> PushTask(FUN&& f, ARGS&&... args)
34     {
35         using ret_type = typename std::invoke_result<FUN, ARGS...>::type;
36         auto task = std::make_shared<std::packaged_task<ret_type()>>(
37             std::bind(std::forward<FUN>(f), std::forward<ARGS>(args)...));
38 
39         auto res = task->get_future();
40         {
41             std::unique_lock<std::mutex> lock(mtx_);
42             tasks_.emplace([task] { (*task)(); });
43         }
44         cond_.notify_one();
45         return res;
46     }
47     ~ThreadPool();
48 
49     void Stop();
50 
51 private:
52     void Run();
53 
54 private:
55     std::vector<std::thread> ths_;
56     std::queue<std::function<void()>> tasks_;
57     std::mutex mtx_;
58     std::condition_variable cond_;
59     std::atomic_bool stop_{false};
60 };
61 }
62 
63 #endif  // THREAD_POOL_H