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
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. struct ThreadContext {
  35. std::mutex mutex;
  36. std::condition_variable cond_var;
  37. const Task *task{nullptr};
  38. };
  39. class ThreadPool {
  40. public:
  41. ~ThreadPool();
  42. ThreadPool(const ThreadPool &) = delete;
  43. ThreadPool &operator=(const ThreadPool &) = delete;
  44. static ThreadPool &GetInstance();
  45. bool SyncRun(const std::vector<Task> &tasks);
  46. size_t GetSyncRunThreadNum() { return max_thread_num_; }
  47. void ClearThreadPool();
  48. private:
  49. ThreadPool();
  50. void SyncRunLoop(const std::shared_ptr<ThreadContext> &context);
  51. size_t max_thread_num_{1};
  52. std::mutex pool_mtx_;
  53. std::atomic_bool exit_run_ = {false};
  54. std::vector<std::thread> sync_run_threads_{};
  55. std::vector<std::shared_ptr<ThreadContext>> contexts_;
  56. };
  57. } // namespace common
  58. } // namespace mindspore
  59. #endif // MINDSPORE_CCSRC_COMMON_THREAD_POOL_H_