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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. is_stoped_.store(true);
  31. cond_var_.notify_all();
  32. for (std::thread &thd : pool_) {
  33. if (thd.joinable()) {
  34. try {
  35. thd.join();
  36. } catch (const std::system_error &) {
  37. } catch (...) {
  38. }
  39. }
  40. }
  41. }
  42. void ThreadPool::ThreadFunc(ThreadPool *thread_pool) {
  43. if (thread_pool == nullptr) {
  44. return;
  45. }
  46. while (!thread_pool->is_stoped_) {
  47. std::function<void()> task;
  48. {
  49. std::unique_lock<std::mutex> lock{thread_pool->m_lock_};
  50. thread_pool->cond_var_.wait(
  51. lock, [thread_pool] { return thread_pool->is_stoped_.load() || !thread_pool->tasks_.empty(); });
  52. if (thread_pool->is_stoped_ && thread_pool->tasks_.empty()) {
  53. return;
  54. }
  55. task = std::move(thread_pool->tasks_.front());
  56. thread_pool->tasks_.pop();
  57. }
  58. --thread_pool->idle_thrd_num_;
  59. task();
  60. ++thread_pool->idle_thrd_num_;
  61. }
  62. }
  63. } // namespace mindspore::serving

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