/** * Copyright 2020 Huawei Technologies 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 MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_ #define MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_ #include #include #include #include #include #include #include #include #include #include #include #include "utils/log_adapter.h" namespace mindspore { const int kCoreThreadNum = 3; const int kDefaultMaxThreadNum = 8; enum Status { FAIL = -1, SUCCESS = 0 }; using Task = std::function; class Queue { public: Queue() = default; ~Queue() = default; bool Enqueue(Task *task); bool Dequeue(Task **out); std::atomic_int task_size_ = {0}; private: std::atomic_int head_ = {0}; std::atomic_int tail_ = {0}; Task *buffer_[2]{}; }; class ThreadPool { public: ~ThreadPool(); ThreadPool(const ThreadPool &) = delete; ThreadPool &operator=(const ThreadPool &) = delete; static ThreadPool *GetInstance(); // Use the tasks' size of threads to execute these tasks, one thread execute one task. bool LaunchMultipleTask(const std::vector &tasks); private: ThreadPool(); bool SetThreadPool(int config_thread_num); void AddNewThread(int add_num); void AddRunThread(int num); void SubRunThread(int num); bool CheckResult(); int cur_thread_nums_{0}; int cur_thread_run_nums_{0}; int core_thread_num_{kCoreThreadNum}; int max_thread_num_{kDefaultMaxThreadNum}; std::mutex pool_mtx_; std::mutex thread_mtx_; std::condition_variable queue_ready_; std::atomic_bool exit_run_ = {false}; std::vector activate_list_{}; std::vector thread_list_{}; std::vector> queue_list_{}; std::vector>> error_info_{}; }; } // namespace mindspore #endif // MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_