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.1 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Copyright 2019-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_SERVING_THREAD_POOL_H_
  17. #define MINDSPORE_SERVING_THREAD_POOL_H_
  18. #include <atomic>
  19. #include <condition_variable>
  20. #include <functional>
  21. #include <future>
  22. #include <memory>
  23. #include <queue>
  24. #include <stdexcept>
  25. #include <thread>
  26. #include <utility>
  27. #include <vector>
  28. namespace mindspore::serving {
  29. using ThreadTask = std::function<void()>;
  30. class ThreadPool {
  31. public:
  32. explicit ThreadPool(uint32_t size = 4);
  33. ~ThreadPool();
  34. template <class Func, class... Args>
  35. auto commit(Func &&func, Args &&... args) -> std::future<decltype(func(args...))> {
  36. using retType = decltype(func(args...));
  37. std::future<retType> fail_future;
  38. if (is_stoped_.load()) {
  39. return fail_future;
  40. }
  41. auto bindFunc = std::bind(std::forward<Func>(func), std::forward<Args>(args)...);
  42. auto task = std::make_shared<std::packaged_task<retType()>>(bindFunc);
  43. if (task == nullptr) {
  44. return fail_future;
  45. }
  46. std::future<retType> future = task->get_future();
  47. {
  48. std::lock_guard<std::mutex> lock{m_lock_};
  49. tasks_.emplace([task]() { (*task)(); });
  50. }
  51. cond_var_.notify_one();
  52. return future;
  53. }
  54. static void ThreadFunc(ThreadPool *thread_pool);
  55. private:
  56. std::vector<std::thread> pool_;
  57. std::queue<ThreadTask> tasks_;
  58. std::mutex m_lock_;
  59. std::condition_variable cond_var_;
  60. std::atomic<bool> is_stoped_;
  61. std::atomic<uint32_t> idle_thrd_num_;
  62. };
  63. } // namespace mindspore::serving
  64. #endif // MINDSPORE_SERVING_THREAD_POOL_H_

A lightweight and high-performance service module that helps MindSpore developers efficiently deploy online inference services in the production environment.