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.

queue.h 6.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /**
  2. * Copyright 2019 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_MINDDATA_DATASET_UTIL_QUEUE_H_
  17. #define MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_QUEUE_H_
  18. #include <atomic>
  19. #include <memory>
  20. #include <mutex>
  21. #include <string>
  22. #include <type_traits>
  23. #include <utility>
  24. #include <vector>
  25. #include "utils/ms_utils.h"
  26. #include "utils/log_adapter.h"
  27. #include "minddata/dataset/util/allocator.h"
  28. #include "minddata/dataset/util/services.h"
  29. #include "minddata/dataset/util/cond_var.h"
  30. #include "minddata/dataset/util/task_manager.h"
  31. namespace mindspore {
  32. namespace dataset {
  33. // A simple thread safe queue using a fixed size array
  34. template <typename T>
  35. class Queue {
  36. public:
  37. using value_type = T;
  38. using pointer = T *;
  39. using const_pointer = const T *;
  40. using reference = T &;
  41. using const_reference = const T &;
  42. explicit Queue(int sz)
  43. : sz_(sz), arr_(Services::GetAllocator<T>()), head_(0), tail_(0), my_name_(Services::GetUniqueID()) {
  44. Status rc = arr_.allocate(sz);
  45. if (rc.IsError()) {
  46. MS_LOG(ERROR) << "Fail to create a queue.";
  47. std::terminate();
  48. } else {
  49. MS_LOG(DEBUG) << "Create Q with uuid " << my_name_ << " of size " << sz_ << ".";
  50. }
  51. }
  52. virtual ~Queue() { ResetQue(); }
  53. size_t size() const {
  54. size_t v = tail_ - head_;
  55. return (v >= 0) ? v : 0;
  56. }
  57. size_t capacity() const { return sz_; }
  58. bool empty() const { return head_ == tail_; }
  59. void Reset() { ResetQue(); }
  60. // Producer
  61. Status Add(const_reference ele) noexcept {
  62. std::unique_lock<std::mutex> _lock(mux_);
  63. // Block when full
  64. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  65. if (rc.IsOk()) {
  66. auto k = tail_++ % sz_;
  67. *(arr_[k]) = ele;
  68. empty_cv_.NotifyAll();
  69. _lock.unlock();
  70. } else {
  71. empty_cv_.Interrupt();
  72. }
  73. return rc;
  74. }
  75. Status Add(T &&ele) noexcept {
  76. std::unique_lock<std::mutex> _lock(mux_);
  77. // Block when full
  78. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  79. if (rc.IsOk()) {
  80. auto k = tail_++ % sz_;
  81. *(arr_[k]) = std::forward<T>(ele);
  82. empty_cv_.NotifyAll();
  83. _lock.unlock();
  84. } else {
  85. empty_cv_.Interrupt();
  86. }
  87. return rc;
  88. }
  89. template <typename... Ts>
  90. Status EmplaceBack(Ts &&... args) noexcept {
  91. std::unique_lock<std::mutex> _lock(mux_);
  92. // Block when full
  93. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  94. if (rc.IsOk()) {
  95. auto k = tail_++ % sz_;
  96. new (arr_[k]) T(std::forward<Ts>(args)...);
  97. empty_cv_.NotifyAll();
  98. _lock.unlock();
  99. } else {
  100. empty_cv_.Interrupt();
  101. }
  102. return rc;
  103. }
  104. // Consumer
  105. Status PopFront(pointer p) {
  106. std::unique_lock<std::mutex> _lock(mux_);
  107. // Block when empty
  108. Status rc = empty_cv_.Wait(&_lock, [this]() -> bool { return !empty(); });
  109. if (rc.IsOk()) {
  110. auto k = head_++ % sz_;
  111. *p = std::move(*(arr_[k]));
  112. full_cv_.NotifyAll();
  113. _lock.unlock();
  114. } else {
  115. full_cv_.Interrupt();
  116. }
  117. return rc;
  118. }
  119. void ResetQue() noexcept {
  120. std::unique_lock<std::mutex> _lock(mux_);
  121. // If there are elements in the queue, drain them. We won't call PopFront directly
  122. // because we have got the lock already. We will deadlock if we call PopFront
  123. for (auto i = head_; i < tail_; ++i) {
  124. auto k = i % sz_;
  125. auto val = std::move(*(arr_[k]));
  126. // Let val go out of scope and its destructor will be invoked automatically.
  127. // But our compiler may complain val is not in use. So let's do some useless
  128. // stuff.
  129. MS_LOG(DEBUG) << "Address of val: " << &val;
  130. }
  131. empty_cv_.ResetIntrpState();
  132. full_cv_.ResetIntrpState();
  133. head_ = 0;
  134. tail_ = 0;
  135. }
  136. Status Register(TaskGroup *vg) {
  137. Status rc1 = empty_cv_.Register(vg->GetIntrpService());
  138. Status rc2 = full_cv_.Register(vg->GetIntrpService());
  139. if (rc1.IsOk()) {
  140. return rc2;
  141. } else {
  142. return rc1;
  143. }
  144. }
  145. private:
  146. size_t sz_;
  147. MemGuard<T, Allocator<T>> arr_;
  148. size_t head_;
  149. size_t tail_;
  150. std::string my_name_;
  151. std::mutex mux_;
  152. CondVar empty_cv_;
  153. CondVar full_cv_;
  154. };
  155. // A container of queues with [] operator accessors. Basically this is a wrapper over of a vector of queues
  156. // to help abstract/simplify code that is maintaining multiple queues.
  157. template <typename T>
  158. class QueueList {
  159. public:
  160. QueueList() {}
  161. void Init(int num_queues, int capacity) {
  162. queue_list_.reserve(num_queues);
  163. for (int i = 0; i < num_queues; i++) {
  164. queue_list_.emplace_back(std::make_unique<Queue<T>>(capacity));
  165. }
  166. }
  167. Status Register(TaskGroup *vg) {
  168. if (vg == nullptr) {
  169. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Null task group during QueueList registration.");
  170. }
  171. for (int i = 0; i < queue_list_.size(); ++i) {
  172. RETURN_IF_NOT_OK(queue_list_[i]->Register(vg));
  173. }
  174. return Status::OK();
  175. }
  176. auto size() const { return queue_list_.size(); }
  177. std::unique_ptr<Queue<T>> &operator[](const int index) { return queue_list_[index]; }
  178. const std::unique_ptr<Queue<T>> &operator[](const int index) const { return queue_list_[index]; }
  179. ~QueueList() = default;
  180. private:
  181. // Queue contains non-copyable objects, so it cannot be added to a vector due to the vector
  182. // requirement that objects must have copy semantics. To resolve this, we use a vector of unique
  183. // pointers. This allows us to provide dynamic creation of queues in a container.
  184. std::vector<std::unique_ptr<Queue<T>>> queue_list_;
  185. };
  186. } // namespace dataset
  187. } // namespace mindspore
  188. #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_QUEUE_H_