/* * Copyright (c) 2021-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef OHOS_RESTOOL_THREAD_POOL_H #define OHOS_RESTOOL_THREAD_POOL_H #include #include #include #include #include #include #include #include namespace OHOS { namespace Global { namespace Restool { class ThreadPool { public: /** * @brief Creates a thread pool with specify thread count * @param threadCount the count of threads to be created */ explicit ThreadPool(const size_t threadCount); ~ThreadPool(); /** * @brief Start the thread pool */ uint32_t Start(); /** * @brief Stop the thread pool */ void Stop(); /** * @brief Enqueue a task to queue of thread pool * @param f the function to execute * @param args the args of the function */ template std::future::type> Enqueue(F &&f, Args &&...args); private: void WorkInThread(); std::vector workerThreads_; std::queue> tasks_; std::mutex queueMutex_; std::condition_variable condition_; bool running_{ false }; size_t threadCount_; }; template std::future::type> ThreadPool::Enqueue(F &&f, Args &&...args) { using return_type = typename std::result_of::type; using p_task = std::packaged_task; auto task = std::make_shared(std::bind(std::forward(f), std::forward(args)...)); std::future res = task->get_future(); { std::unique_lock lock(queueMutex_); tasks_.emplace([task]() { (*task)(); }); } condition_.notify_one(); return res; } } // namespace Restool } // namespace Global } // namespace OHOS #endif