You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

thread_pool.h 1.9 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. #ifndef MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_
  17. #define MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_
  18. #include <mutex>
  19. #include <condition_variable>
  20. #include <thread>
  21. #include <vector>
  22. #include <queue>
  23. #include <string>
  24. #include <atomic>
  25. #include <memory>
  26. #include <utility>
  27. #include <functional>
  28. #include <iostream>
  29. #include "utils/log_adapter.h"
  30. namespace mindspore {
  31. namespace common {
  32. enum Status { FAIL = -1, SUCCESS = 0 };
  33. using Task = std::function<int()>;
  34. class ThreadPool {
  35. public:
  36. ~ThreadPool();
  37. ThreadPool(const ThreadPool &) = delete;
  38. ThreadPool &operator=(const ThreadPool &) = delete;
  39. static ThreadPool &GetInstance();
  40. bool SyncRun(const std::vector<Task> &tasks);
  41. size_t GetSyncRunThreadNum() { return max_thread_num_; }
  42. void ClearThreadPool();
  43. private:
  44. ThreadPool();
  45. void SyncRunLoop();
  46. size_t max_thread_num_{1};
  47. std::mutex pool_mtx_;
  48. std::atomic_bool exit_run_ = {false};
  49. std::queue<Task> task_queue_;
  50. std::mutex task_mutex_;
  51. std::condition_variable task_cond_var_;
  52. size_t task_finished_count_{0};
  53. std::condition_variable finished_cond_var_;
  54. std::vector<std::thread> sync_run_threads_{};
  55. };
  56. } // namespace common
  57. } // namespace mindspore
  58. #endif // MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_