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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 DATASET_UTIL_QUEUE_H_
  17. #define 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 "common/utils.h"
  26. #include "dataset/util/de_error.h"
  27. #include "utils/log_adapter.h"
  28. #include "dataset/util/allocator.h"
  29. #include "dataset/util/services.h"
  30. #include "dataset/util/cond_var.h"
  31. #include "dataset/util/task_manager.h"
  32. namespace mindspore {
  33. namespace dataset {
  34. template <typename T>
  35. struct is_shared_ptr : public std::false_type {};
  36. template <typename T>
  37. struct is_shared_ptr<std::shared_ptr<T>> : public std::true_type {};
  38. template <typename T>
  39. struct is_unique_ptr : public std::false_type {};
  40. template <typename T>
  41. struct is_unique_ptr<std::unique_ptr<T>> : public std::true_type {};
  42. // A simple thread safe queue using a fixed size array
  43. template <typename T>
  44. class Queue {
  45. public:
  46. using value_type = T;
  47. using pointer = T *;
  48. using const_pointer = const T *;
  49. using reference = T &;
  50. using const_reference = const T &;
  51. void Init() {
  52. if (sz_ > 0) {
  53. // We allocate a block of memory and then call the default constructor for each slot. Maybe simpler to call
  54. // new[] but we want to control where the memory is allocated from.
  55. arr_ = alloc_.allocate(sz_);
  56. for (uint64_t i = 0; i < sz_; i++) {
  57. std::allocator_traits<Allocator<T>>::construct(alloc_, &(arr_[i]));
  58. }
  59. }
  60. }
  61. explicit Queue(int sz)
  62. : sz_(sz),
  63. arr_(nullptr),
  64. head_(0),
  65. tail_(0),
  66. my_name_(std::move(Services::GetUniqueID())),
  67. alloc_(Services::GetInstance().GetServiceMemPool()) {
  68. Init();
  69. MS_LOG(DEBUG) << "Create Q with uuid " << my_name_ << " of size " << sz_ << ".";
  70. }
  71. virtual ~Queue() {
  72. ResetQue();
  73. if (arr_) {
  74. // Simply free the pointer. Since there is nothing in the queue. We don't want to invoke the destructor
  75. // of T in each slot.
  76. alloc_.deallocate(arr_);
  77. arr_ = nullptr;
  78. }
  79. }
  80. int size() const {
  81. int v = tail_ - head_;
  82. return (v >= 0) ? v : 0;
  83. }
  84. int capacity() const { return sz_; }
  85. bool empty() const { return head_ == tail_; }
  86. void Reset() { ResetQue(); }
  87. // Producer
  88. Status Add(const_reference ele) noexcept {
  89. std::unique_lock<std::mutex> _lock(mux_);
  90. // Block when full
  91. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  92. if (rc.IsOk()) {
  93. uint32_t k = tail_++ % sz_;
  94. arr_[k] = ele;
  95. empty_cv_.NotifyAll();
  96. _lock.unlock();
  97. } else {
  98. (void)empty_cv_.Interrupt();
  99. }
  100. return rc;
  101. }
  102. Status Add(T &&ele) noexcept {
  103. std::unique_lock<std::mutex> _lock(mux_);
  104. // Block when full
  105. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  106. if (rc.IsOk()) {
  107. uint32_t k = tail_++ % sz_;
  108. arr_[k] = std::forward<T>(ele);
  109. empty_cv_.NotifyAll();
  110. _lock.unlock();
  111. } else {
  112. (void)empty_cv_.Interrupt();
  113. }
  114. return rc;
  115. }
  116. template <typename... Ts>
  117. Status EmplaceBack(Ts &&... args) noexcept {
  118. std::unique_lock<std::mutex> _lock(mux_);
  119. // Block when full
  120. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  121. if (rc.IsOk()) {
  122. uint32_t k = tail_++ % sz_;
  123. new (&(arr_[k])) T(std::forward<Ts>(args)...);
  124. empty_cv_.NotifyAll();
  125. _lock.unlock();
  126. } else {
  127. (void)empty_cv_.Interrupt();
  128. }
  129. return rc;
  130. }
  131. // Consumer
  132. Status PopFront(pointer p) {
  133. std::unique_lock<std::mutex> _lock(mux_);
  134. // Block when empty
  135. Status rc = empty_cv_.Wait(&_lock, [this]() -> bool { return !empty(); });
  136. if (rc.IsOk()) {
  137. uint32_t k = head_++ % sz_;
  138. *p = std::move(arr_[k]);
  139. if (std::is_destructible<T>::value) {
  140. arr_[k].~T();
  141. }
  142. full_cv_.NotifyAll();
  143. _lock.unlock();
  144. } else {
  145. (void)full_cv_.Interrupt();
  146. }
  147. return rc;
  148. }
  149. void ResetQue() noexcept {
  150. std::unique_lock<std::mutex> _lock(mux_);
  151. // If there are elements in the queue, invoke its destructor one by one.
  152. if (!empty() && std::is_destructible<T>::value) {
  153. for (uint64_t i = head_; i < tail_; i++) {
  154. uint32_t k = i % sz_;
  155. arr_[k].~T();
  156. }
  157. }
  158. empty_cv_.ResetIntrpState();
  159. full_cv_.ResetIntrpState();
  160. head_ = 0;
  161. tail_ = 0;
  162. }
  163. Status Register(TaskGroup *vg) {
  164. Status rc1 = empty_cv_.Register(vg->GetIntrpService());
  165. Status rc2 = full_cv_.Register(vg->GetIntrpService());
  166. if (rc1.IsOk()) {
  167. return rc2;
  168. } else {
  169. return rc1;
  170. }
  171. }
  172. private:
  173. uint64_t sz_;
  174. pointer arr_;
  175. uint64_t head_;
  176. uint64_t tail_;
  177. std::string my_name_;
  178. std::mutex mux_;
  179. CondVar empty_cv_;
  180. CondVar full_cv_;
  181. Allocator<T> alloc_;
  182. };
  183. // A container of queues with [] operator accessors. Basically this is a wrapper over of a vector of queues
  184. // to help abstract/simplify code that is maintaining multiple queues.
  185. template <typename T>
  186. class QueueList {
  187. public:
  188. QueueList() {}
  189. void Init(int num_queues, int capacity) {
  190. queue_list_.reserve(num_queues);
  191. for (int i = 0; i < num_queues; i++) {
  192. queue_list_.emplace_back(std::make_unique<Queue<T>>(capacity));
  193. }
  194. }
  195. Status Register(TaskGroup *vg) {
  196. if (vg == nullptr) {
  197. return Status(StatusCode::kUnexpectedError, __LINE__, __FILE__, "Null task group during QueueList registration.");
  198. }
  199. for (int i = 0; i < queue_list_.size(); ++i) {
  200. RETURN_IF_NOT_OK(queue_list_[i]->Register(vg));
  201. }
  202. return Status::OK();
  203. }
  204. int size() const { return queue_list_.size(); }
  205. std::unique_ptr<Queue<T>> &operator[](const int index) { return queue_list_[index]; }
  206. ~QueueList() = default;
  207. private:
  208. // Queue contains non-copyable objects, so it cannot be added to a vector due to the vector
  209. // requirement that objects must have copy semantics. To resolve this, we use a vector of unique
  210. // pointers. This allows us to provide dynamic creation of queues in a container.
  211. std::vector<std::unique_ptr<Queue<T>>> queue_list_;
  212. };
  213. } // namespace dataset
  214. } // namespace mindspore
  215. #endif // DATASET_UTIL_QUEUE_H_