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

4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. /**
  2. * Copyright 2019-2021 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() {
  61. std::unique_lock<std::mutex> _lock(mux_);
  62. ResetQue();
  63. extra_arr_.clear();
  64. }
  65. // Producer
  66. Status Add(const_reference ele) noexcept {
  67. std::unique_lock<std::mutex> _lock(mux_);
  68. // Block when full
  69. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  70. if (rc.IsOk()) {
  71. RETURN_IF_NOT_OK(AddWhileHoldingLock(ele));
  72. empty_cv_.NotifyAll();
  73. _lock.unlock();
  74. } else {
  75. empty_cv_.Interrupt();
  76. }
  77. return rc;
  78. }
  79. Status Add(T &&ele) noexcept {
  80. std::unique_lock<std::mutex> _lock(mux_);
  81. // Block when full
  82. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  83. if (rc.IsOk()) {
  84. RETURN_IF_NOT_OK(AddWhileHoldingLock(std::forward<T>(ele)));
  85. empty_cv_.NotifyAll();
  86. _lock.unlock();
  87. } else {
  88. empty_cv_.Interrupt();
  89. }
  90. return rc;
  91. }
  92. template <typename... Ts>
  93. Status EmplaceBack(Ts &&... args) noexcept {
  94. std::unique_lock<std::mutex> _lock(mux_);
  95. // Block when full
  96. Status rc = full_cv_.Wait(&_lock, [this]() -> bool { return (size() != capacity()); });
  97. if (rc.IsOk()) {
  98. auto k = tail_++ % sz_;
  99. new (arr_[k]) T(std::forward<Ts>(args)...);
  100. empty_cv_.NotifyAll();
  101. _lock.unlock();
  102. } else {
  103. empty_cv_.Interrupt();
  104. }
  105. return rc;
  106. }
  107. // Consumer
  108. Status PopFront(pointer p) {
  109. std::unique_lock<std::mutex> _lock(mux_);
  110. // Block when empty
  111. Status rc = empty_cv_.Wait(&_lock, [this]() -> bool { return !empty(); });
  112. if (rc.IsOk()) {
  113. RETURN_IF_NOT_OK(PopFrontWhileHoldingLock(p, true));
  114. full_cv_.NotifyAll();
  115. _lock.unlock();
  116. } else {
  117. full_cv_.Interrupt();
  118. }
  119. return rc;
  120. }
  121. Status Register(TaskGroup *vg) {
  122. Status rc1 = empty_cv_.Register(vg->GetIntrpService());
  123. Status rc2 = full_cv_.Register(vg->GetIntrpService());
  124. if (rc1.IsOk()) {
  125. return rc2;
  126. } else {
  127. return rc1;
  128. }
  129. }
  130. Status Resize(int32_t new_capacity) {
  131. std::unique_lock<std::mutex> _lock(mux_);
  132. CHECK_FAIL_RETURN_UNEXPECTED(new_capacity > 0,
  133. "New capacity: " + std::to_string(new_capacity) + ", should be larger than 0");
  134. RETURN_OK_IF_TRUE(new_capacity == static_cast<int32_t>(capacity()));
  135. std::vector<T> queue;
  136. // pop from the original queue until the new_capacity is full
  137. for (int32_t i = 0; i < new_capacity; ++i) {
  138. if (head_ < tail_) {
  139. // if there are elements left in queue, pop out
  140. T temp;
  141. RETURN_IF_NOT_OK(this->PopFrontWhileHoldingLock(&temp, true));
  142. queue.push_back(temp);
  143. } else {
  144. // if there is nothing left in queue, check extra_arr_
  145. if (!extra_arr_.empty()) {
  146. // if extra_arr_ is not empty, push to fill the new_capacity
  147. queue.push_back(extra_arr_[0]);
  148. extra_arr_.erase(extra_arr_.begin());
  149. } else {
  150. // if everything in the queue and extra_arr_ is popped out, break the loop
  151. break;
  152. }
  153. }
  154. }
  155. // if there are extra elements in queue, put them to extra_arr_
  156. while (head_ < tail_) {
  157. T temp;
  158. RETURN_IF_NOT_OK(this->PopFrontWhileHoldingLock(&temp, false));
  159. extra_arr_.push_back(temp);
  160. }
  161. this->ResetQue();
  162. RETURN_IF_NOT_OK(arr_.allocate(new_capacity));
  163. sz_ = new_capacity;
  164. for (int32_t i = 0; i < static_cast<int32_t>(queue.size()); ++i) {
  165. RETURN_IF_NOT_OK(this->AddWhileHoldingLock(queue[i]));
  166. }
  167. queue.clear();
  168. _lock.unlock();
  169. return Status::OK();
  170. }
  171. private:
  172. size_t sz_;
  173. MemGuard<T, Allocator<T>> arr_;
  174. std::vector<T> extra_arr_; // used to store extra elements after reducing capacity, will not be changed by Add,
  175. // will pop when there is a space in queue (by PopFront or Resize)
  176. size_t head_;
  177. size_t tail_;
  178. std::string my_name_;
  179. std::mutex mux_;
  180. CondVar empty_cv_;
  181. CondVar full_cv_;
  182. // Helper function for Add, must be called when holding a lock
  183. Status AddWhileHoldingLock(const_reference ele) {
  184. auto k = tail_++ % sz_;
  185. *(arr_[k]) = ele;
  186. return Status::OK();
  187. }
  188. // Helper function for Add, must be called when holding a lock
  189. Status AddWhileHoldingLock(T &&ele) {
  190. auto k = tail_++ % sz_;
  191. *(arr_[k]) = std::forward<T>(ele);
  192. return Status::OK();
  193. }
  194. // Helper function for PopFront, must be called when holding a lock
  195. Status PopFrontWhileHoldingLock(pointer p, bool clean_extra) {
  196. auto k = head_++ % sz_;
  197. *p = std::move(*(arr_[k]));
  198. if (!extra_arr_.empty() && clean_extra) {
  199. RETURN_IF_NOT_OK(this->AddWhileHoldingLock(std::forward<T>(extra_arr_[0])));
  200. extra_arr_.erase(extra_arr_.begin());
  201. }
  202. return Status::OK();
  203. }
  204. void ResetQue() noexcept {
  205. while (head_ < tail_) {
  206. T val;
  207. this->PopFrontWhileHoldingLock(&val, false);
  208. MS_LOG(DEBUG) << "Address of val: " << &val;
  209. }
  210. empty_cv_.ResetIntrpState();
  211. full_cv_.ResetIntrpState();
  212. head_ = 0;
  213. tail_ = 0;
  214. }
  215. };
  216. // A container of queues with [] operator accessors. Basically this is a wrapper over of a vector of queues
  217. // to help abstract/simplify code that is maintaining multiple queues.
  218. template <typename T>
  219. class QueueList {
  220. public:
  221. QueueList() {}
  222. void Init(int num_queues, int capacity) {
  223. queue_list_.reserve(num_queues);
  224. for (int i = 0; i < num_queues; i++) {
  225. queue_list_.emplace_back(std::make_unique<Queue<T>>(capacity));
  226. }
  227. }
  228. Status Register(TaskGroup *vg) {
  229. if (vg == nullptr) {
  230. return Status(StatusCode::kMDUnexpectedError, __LINE__, __FILE__,
  231. "Null task group during QueueList registration.");
  232. }
  233. for (int i = 0; i < queue_list_.size(); ++i) {
  234. RETURN_IF_NOT_OK(queue_list_[i]->Register(vg));
  235. }
  236. return Status::OK();
  237. }
  238. auto size() const { return queue_list_.size(); }
  239. std::unique_ptr<Queue<T>> &operator[](const int index) { return queue_list_[index]; }
  240. const std::unique_ptr<Queue<T>> &operator[](const int index) const { return queue_list_[index]; }
  241. ~QueueList() = default;
  242. Status AddQueue(TaskGroup *vg) {
  243. queue_list_.emplace_back(std::make_unique<Queue<T>>(queue_list_[0]->capacity()));
  244. return queue_list_[queue_list_.size() - 1]->Register(vg);
  245. }
  246. Status RemoveLastQueue() {
  247. CHECK_FAIL_RETURN_UNEXPECTED(queue_list_.size() > 1, "Cannot remove more than the current queues.");
  248. queue_list_.pop_back();
  249. return Status::OK();
  250. }
  251. private:
  252. // Queue contains non-copyable objects, so it cannot be added to a vector due to the vector
  253. // requirement that objects must have copy semantics. To resolve this, we use a vector of unique
  254. // pointers. This allows us to provide dynamic creation of queues in a container.
  255. std::vector<std::unique_ptr<Queue<T>>> queue_list_;
  256. };
  257. } // namespace dataset
  258. } // namespace mindspore
  259. #endif // MINDSPORE_CCSRC_MINDDATA_DATASET_UTIL_QUEUE_H_