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

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