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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include "common/thread_pool.h"
  17. #include <atomic>
  18. #include <functional>
  19. #include <queue>
  20. #include <stdexcept>
  21. #include <utility>
  22. #include <vector>
  23. namespace mindspore::serving {
  24. ThreadPool::ThreadPool(uint32_t size) : is_stoped_(false), idle_thrd_num_(size < 1 ? 1 : size) {
  25. for (uint32_t i = 0; i < idle_thrd_num_; ++i) {
  26. pool_.emplace_back(ThreadFunc, this);
  27. }
  28. }
  29. ThreadPool::~ThreadPool() {
  30. {
  31. std::unique_lock<std::mutex> lock{m_lock_};
  32. is_stoped_.store(true);
  33. cond_var_.notify_all();
  34. }
  35. for (std::thread &thd : pool_) {
  36. if (thd.joinable()) {
  37. try {
  38. thd.join();
  39. } catch (const std::system_error &) {
  40. } catch (...) {
  41. }
  42. }
  43. }
  44. }
  45. void ThreadPool::ThreadFunc(ThreadPool *thread_pool) {
  46. if (thread_pool == nullptr) {
  47. return;
  48. }
  49. while (!thread_pool->is_stoped_) {
  50. std::function<void()> task;
  51. {
  52. std::unique_lock<std::mutex> lock{thread_pool->m_lock_};
  53. thread_pool->cond_var_.wait(
  54. lock, [thread_pool] { return thread_pool->is_stoped_.load() || !thread_pool->tasks_.empty(); });
  55. if (thread_pool->is_stoped_ && thread_pool->tasks_.empty()) {
  56. return;
  57. }
  58. task = std::move(thread_pool->tasks_.front());
  59. thread_pool->tasks_.pop();
  60. }
  61. --thread_pool->idle_thrd_num_;
  62. task();
  63. ++thread_pool->idle_thrd_num_;
  64. }
  65. }
  66. } // namespace mindspore::serving

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