1 /*
2 * Copyright (c) 2021-2024 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 OHOS_RESTOOL_THREAD_POOL_H
17 #define OHOS_RESTOOL_THREAD_POOL_H
18
19 #include <condition_variable>
20 #include <functional>
21 #include <future>
22 #include <mutex>
23 #include <queue>
24 #include <string>
25 #include <thread>
26 #include <vector>
27
28 namespace OHOS {
29 namespace Global {
30 namespace Restool {
31 class ThreadPool {
32 public:
33 ~ThreadPool();
34
35 /**
36 * @brief Start the thread pool
37 * @param threadCount the count of thread pool
38 */
39 uint32_t Start(const size_t &threadCount);
40
41 /**
42 * @brief Stop the thread pool
43 */
44 void Stop();
45
46 /**
47 * @brief Enqueue a task to queue of thread pool
48 * @param f the function to execute
49 * @param args the args of the function
50 */
51 template <class F, class... Args>
52 std::future<typename std::result_of<F(Args...)>::type> Enqueue(F &&f, Args &&...args);
53
54 static ThreadPool &GetInstance();
55
56 private:
57 ThreadPool();
58 ThreadPool(const ThreadPool &) = delete;
59 ThreadPool &operator=(const ThreadPool &) = delete;
60 void WorkInThread();
61 std::vector<std::thread> workerThreads_;
62 std::queue<std::function<void()>> tasks_;
63
64 std::mutex queueMutex_;
65 std::condition_variable condition_;
66 bool running_{ false };
67 };
68
69 template <typename F, typename... Args>
Enqueue(F && f,Args &&...args)70 std::future<typename std::result_of<F(Args...)>::type> ThreadPool::Enqueue(F &&f, Args &&...args)
71 {
72 using return_type = typename std::result_of<F(Args...)>::type;
73 using p_task = std::packaged_task<return_type()>;
74 auto task = std::make_shared<p_task>(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
75
76 std::future<return_type> res = task->get_future();
77 {
78 std::unique_lock<std::mutex> lock(queueMutex_);
79 tasks_.emplace([task]() { (*task)(); });
80 }
81 condition_.notify_one();
82 return res;
83 }
84 } // namespace Restool
85 } // namespace Global
86 } // namespace OHOS
87 #endif
88