• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2020 Huawei Technologies Co., Ltd
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_
18 #define MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_
19 
20 #include <mutex>
21 #include <condition_variable>
22 #include <thread>
23 #include <vector>
24 #include <queue>
25 #include <string>
26 #include <atomic>
27 #include <memory>
28 #include <utility>
29 #include <functional>
30 #include <iostream>
31 #include "utils/log_adapter.h"
32 
33 namespace mindspore {
34 namespace common {
35 enum Status { FAIL = -1, SUCCESS = 0 };
36 using Task = std::function<int()>;
37 
38 class ThreadPool {
39  public:
40   ~ThreadPool();
41   ThreadPool(const ThreadPool &) = delete;
42   ThreadPool &operator=(const ThreadPool &) = delete;
43   static ThreadPool &GetInstance();
44   bool SyncRun(const std::vector<Task> &tasks);
GetSyncRunThreadNum()45   size_t GetSyncRunThreadNum() { return max_thread_num_; }
46   void ClearThreadPool();
47 
48  private:
49   ThreadPool();
50   void SyncRunLoop();
51 
52   size_t max_thread_num_{1};
53   std::mutex pool_mtx_;
54   std::atomic_bool exit_run_ = {false};
55   std::queue<Task> task_queue_;
56   std::mutex task_mutex_;
57   std::condition_variable task_cond_var_;
58   size_t task_finished_count_{0};
59   std::condition_variable finished_cond_var_;
60   std::vector<std::thread> sync_run_threads_{};
61 };
62 }  // namespace common
63 }  // namespace mindspore
64 
65 #endif  // MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_
66