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 2.0 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * Copyright 2020-2022 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_INCLUDE_COMMON_THREAD_POOL_H_
  17. #define MINDSPORE_CCSRC_INCLUDE_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. #include "include/common/visible.h"
  31. namespace mindspore {
  32. namespace common {
  33. enum Status { FAIL = -1, SUCCESS = 0 };
  34. using Task = std::function<Status()>;
  35. struct ThreadContext {
  36. std::mutex mutex;
  37. std::condition_variable cond_var;
  38. const Task *task{nullptr};
  39. };
  40. class COMMON_EXPORT ThreadPool {
  41. public:
  42. ~ThreadPool();
  43. ThreadPool(const ThreadPool &) = delete;
  44. ThreadPool &operator=(const ThreadPool &) = delete;
  45. static ThreadPool &GetInstance();
  46. bool SyncRun(const std::vector<Task> &tasks);
  47. size_t GetSyncRunThreadNum() const { return max_thread_num_; }
  48. void ClearThreadPool();
  49. private:
  50. ThreadPool();
  51. void SyncRunLoop(const std::shared_ptr<ThreadContext> &context);
  52. size_t max_thread_num_{1};
  53. std::mutex pool_mtx_;
  54. std::atomic_bool exit_run_ = {false};
  55. std::vector<std::thread> sync_run_threads_{};
  56. std::vector<std::shared_ptr<ThreadContext>> contexts_;
  57. };
  58. } // namespace common
  59. } // namespace mindspore
  60. #endif // MINDSPORE_CCSRC_INCLUDE_COMMON_THREAD_POOL_H_