• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef RTC_BASE_SWAP_QUEUE_H_
12 #define RTC_BASE_SWAP_QUEUE_H_
13 
14 #include <stddef.h>
15 
16 #include <atomic>
17 #include <utility>
18 #include <vector>
19 
20 #include "rtc_base/checks.h"
21 #include "rtc_base/system/unused.h"
22 
23 namespace webrtc {
24 
25 namespace internal {
26 
27 // (Internal; please don't use outside this file.)
28 template <typename T>
NoopSwapQueueItemVerifierFunction(const T &)29 bool NoopSwapQueueItemVerifierFunction(const T&) {
30   return true;
31 }
32 
33 }  // namespace internal
34 
35 // Functor to use when supplying a verifier function for the queue.
36 template <typename T,
37           bool (*QueueItemVerifierFunction)(const T&) =
38               internal::NoopSwapQueueItemVerifierFunction>
39 class SwapQueueItemVerifier {
40  public:
operator()41   bool operator()(const T& t) const { return QueueItemVerifierFunction(t); }
42 };
43 
44 // This class is a fixed-size queue. A single producer calls Insert() to insert
45 // an element of type T at the back of the queue, and a single consumer calls
46 // Remove() to remove an element from the front of the queue. It's safe for the
47 // producer and the consumer to access the queue concurrently, from different
48 // threads.
49 //
50 // To avoid the construction, copying, and destruction of Ts that a naive
51 // queue implementation would require, for each "full" T passed from
52 // producer to consumer, SwapQueue<T> passes an "empty" T in the other
53 // direction (an "empty" T is one that contains nothing of value for the
54 // consumer). This bidirectional movement is implemented with swap().
55 //
56 // // Create queue:
57 // Bottle proto(568);  // Prepare an empty Bottle. Heap allocates space for
58 //                     // 568 ml.
59 // SwapQueue<Bottle> q(N, proto);  // Init queue with N copies of proto.
60 //                                 // Each copy allocates on the heap.
61 // // Producer pseudo-code:
62 // Bottle b(568); // Prepare an empty Bottle. Heap allocates space for 568 ml.
63 // loop {
64 //   b.Fill(amount);  // Where amount <= 568 ml.
65 //   q.Insert(&b);    // Swap our full Bottle for an empty one from q.
66 // }
67 //
68 // // Consumer pseudo-code:
69 // Bottle b(568);  // Prepare an empty Bottle. Heap allocates space for 568 ml.
70 // loop {
71 //   q.Remove(&b); // Swap our empty Bottle for the next-in-line full Bottle.
72 //   Drink(&b);
73 // }
74 //
75 // For a well-behaved Bottle class, there are no allocations in the
76 // producer, since it just fills an empty Bottle that's already large
77 // enough; no deallocations in the consumer, since it returns each empty
78 // Bottle to the queue after having drunk it; and no copies along the
79 // way, since the queue uses swap() everywhere to move full Bottles in
80 // one direction and empty ones in the other.
81 template <typename T, typename QueueItemVerifier = SwapQueueItemVerifier<T>>
82 class SwapQueue {
83  public:
84   // Creates a queue of size size and fills it with default constructed Ts.
SwapQueue(size_t size)85   explicit SwapQueue(size_t size) : queue_(size) {
86     RTC_DCHECK(VerifyQueueSlots());
87   }
88 
89   // Same as above and accepts an item verification functor.
SwapQueue(size_t size,const QueueItemVerifier & queue_item_verifier)90   SwapQueue(size_t size, const QueueItemVerifier& queue_item_verifier)
91       : queue_item_verifier_(queue_item_verifier), queue_(size) {
92     RTC_DCHECK(VerifyQueueSlots());
93   }
94 
95   // Creates a queue of size size and fills it with copies of prototype.
SwapQueue(size_t size,const T & prototype)96   SwapQueue(size_t size, const T& prototype) : queue_(size, prototype) {
97     RTC_DCHECK(VerifyQueueSlots());
98   }
99 
100   // Same as above and accepts an item verification functor.
SwapQueue(size_t size,const T & prototype,const QueueItemVerifier & queue_item_verifier)101   SwapQueue(size_t size,
102             const T& prototype,
103             const QueueItemVerifier& queue_item_verifier)
104       : queue_item_verifier_(queue_item_verifier), queue_(size, prototype) {
105     RTC_DCHECK(VerifyQueueSlots());
106   }
107 
108   // Resets the queue to have zero content while maintaining the queue size.
109   // Just like Remove(), this can only be called (safely) from the
110   // consumer.
Clear()111   void Clear() {
112     // Drop all non-empty elements by resetting num_elements_ and incrementing
113     // next_read_index_ by the previous value of num_elements_. Relaxed memory
114     // ordering is sufficient since the dropped elements are not accessed.
115     next_read_index_ += std::atomic_exchange_explicit(
116         &num_elements_, size_t{0}, std::memory_order_relaxed);
117     if (next_read_index_ >= queue_.size()) {
118       next_read_index_ -= queue_.size();
119     }
120 
121     RTC_DCHECK_LT(next_read_index_, queue_.size());
122   }
123 
124   // Inserts a "full" T at the back of the queue by swapping *input with an
125   // "empty" T from the queue.
126   // Returns true if the item was inserted or false if not (the queue was full).
127   // When specified, the T given in *input must pass the ItemVerifier() test.
128   // The contents of *input after the call are then also guaranteed to pass the
129   // ItemVerifier() test.
Insert(T * input)130   bool Insert(T* input) RTC_WARN_UNUSED_RESULT {
131     RTC_DCHECK(input);
132 
133     RTC_DCHECK(queue_item_verifier_(*input));
134 
135     // Load the value of num_elements_. Acquire memory ordering prevents reads
136     // and writes to queue_[next_write_index_] to be reordered to before the
137     // load. (That element might be accessed by a concurrent call to Remove()
138     // until the load finishes.)
139     if (std::atomic_load_explicit(&num_elements_, std::memory_order_acquire) ==
140         queue_.size()) {
141       return false;
142     }
143 
144     std::swap(*input, queue_[next_write_index_]);
145 
146     // Increment the value of num_elements_ to account for the inserted element.
147     // Release memory ordering prevents the reads and writes to
148     // queue_[next_write_index_] to be reordered to after the increment. (Once
149     // the increment has finished, Remove() might start accessing that element.)
150     const size_t old_num_elements = std::atomic_fetch_add_explicit(
151         &num_elements_, size_t{1}, std::memory_order_release);
152 
153     ++next_write_index_;
154     if (next_write_index_ == queue_.size()) {
155       next_write_index_ = 0;
156     }
157 
158     RTC_DCHECK_LT(next_write_index_, queue_.size());
159     RTC_DCHECK_LT(old_num_elements, queue_.size());
160 
161     return true;
162   }
163 
164   // Removes the frontmost "full" T from the queue by swapping it with
165   // the "empty" T in *output.
166   // Returns true if an item could be removed or false if not (the queue was
167   // empty). When specified, The T given in *output must pass the ItemVerifier()
168   // test and the contents of *output after the call are then also guaranteed to
169   // pass the ItemVerifier() test.
Remove(T * output)170   bool Remove(T* output) RTC_WARN_UNUSED_RESULT {
171     RTC_DCHECK(output);
172 
173     RTC_DCHECK(queue_item_verifier_(*output));
174 
175     // Load the value of num_elements_. Acquire memory ordering prevents reads
176     // and writes to queue_[next_read_index_] to be reordered to before the
177     // load. (That element might be accessed by a concurrent call to Insert()
178     // until the load finishes.)
179     if (std::atomic_load_explicit(&num_elements_, std::memory_order_acquire) ==
180         0) {
181       return false;
182     }
183 
184     std::swap(*output, queue_[next_read_index_]);
185 
186     // Decrement the value of num_elements_ to account for the removed element.
187     // Release memory ordering prevents the reads and writes to
188     // queue_[next_write_index_] to be reordered to after the decrement. (Once
189     // the decrement has finished, Insert() might start accessing that element.)
190     std::atomic_fetch_sub_explicit(&num_elements_, size_t{1},
191                                    std::memory_order_release);
192 
193     ++next_read_index_;
194     if (next_read_index_ == queue_.size()) {
195       next_read_index_ = 0;
196     }
197 
198     RTC_DCHECK_LT(next_read_index_, queue_.size());
199 
200     return true;
201   }
202 
203   // Returns the current number of elements in the queue. Since elements may be
204   // concurrently added to the queue, the caller must treat this as a lower
205   // bound, not an exact count.
206   // May only be called by the consumer.
SizeAtLeast()207   size_t SizeAtLeast() const {
208     // Acquire memory ordering ensures that we wait for the producer to finish
209     // inserting any element in progress.
210     return std::atomic_load_explicit(&num_elements_, std::memory_order_acquire);
211   }
212 
213  private:
214   // Verify that the queue slots complies with the ItemVerifier test. This
215   // function is not thread-safe and can only be used in the constructors.
VerifyQueueSlots()216   bool VerifyQueueSlots() {
217     for (const auto& v : queue_) {
218       RTC_DCHECK(queue_item_verifier_(v));
219     }
220     return true;
221   }
222 
223   // TODO(peah): Change this to use std::function() once we can use C++11 std
224   // lib.
225   QueueItemVerifier queue_item_verifier_;
226 
227   // Only accessed by the single producer.
228   size_t next_write_index_ = 0;
229 
230   // Only accessed by the single consumer.
231   size_t next_read_index_ = 0;
232 
233   // Accessed by both the producer and the consumer and used for synchronization
234   // between them.
235   std::atomic<size_t> num_elements_{0};
236 
237   // The elements of the queue are acced by both the producer and the consumer,
238   // mediated by num_elements_. queue_.size() is constant.
239   std::vector<T> queue_;
240 
241   SwapQueue(const SwapQueue&) = delete;
242   SwapQueue& operator=(const SwapQueue&) = delete;
243 };
244 
245 }  // namespace webrtc
246 
247 #endif  // RTC_BASE_SWAP_QUEUE_H_
248