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