blob: eb0b1fff0c3096af3f16fe47164a489d5bcb7ff9 [file] [log] [blame]
peah48407f72015-11-09 05:24:50 -08001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef RTC_BASE_SWAP_QUEUE_H_
12#define RTC_BASE_SWAP_QUEUE_H_
peah48407f72015-11-09 05:24:50 -080013
Yves Gerey3e707812018-11-28 16:47:49 +010014#include <stddef.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +020016#include <atomic>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020017#include <utility>
18#include <vector>
peah48407f72015-11-09 05:24:50 -080019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020021#include "rtc_base/system/unused.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020022
23namespace webrtc {
24
25namespace internal {
26
27// (Internal; please don't use outside this file.)
28template <typename T>
29bool NoopSwapQueueItemVerifierFunction(const T&) {
30 return true;
31}
32
33} // namespace internal
34
35// Functor to use when supplying a verifier function for the queue.
36template <typename T,
37 bool (*QueueItemVerifierFunction)(const T&) =
38 internal::NoopSwapQueueItemVerifierFunction>
39class SwapQueueItemVerifier {
40 public:
41 bool operator()(const T& t) const { return QueueItemVerifierFunction(t); }
42};
43
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +020044// 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.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020049//
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.
81template <typename T, typename QueueItemVerifier = SwapQueueItemVerifier<T>>
82class SwapQueue {
83 public:
84 // Creates a queue of size size and fills it with default constructed Ts.
85 explicit SwapQueue(size_t size) : queue_(size) {
86 RTC_DCHECK(VerifyQueueSlots());
87 }
88
89 // Same as above and accepts an item verification functor.
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.
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.
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
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200108 // 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.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200111 void Clear() {
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200112 // 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());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200122 }
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.
130 bool Insert(T* input) RTC_WARN_UNUSED_RESULT {
131 RTC_DCHECK(input);
132
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200133 RTC_DCHECK(queue_item_verifier_(*input));
134
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200135 // 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()) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200141 return false;
142 }
143
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200144 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);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200152
153 ++next_write_index_;
154 if (next_write_index_ == queue_.size()) {
155 next_write_index_ = 0;
156 }
157
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200158 RTC_DCHECK_LT(next_write_index_, queue_.size());
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200159 RTC_DCHECK_LT(old_num_elements, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200160
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.
170 bool Remove(T* output) RTC_WARN_UNUSED_RESULT {
171 RTC_DCHECK(output);
172
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200173 RTC_DCHECK(queue_item_verifier_(*output));
174
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200175 // 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) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200181 return false;
182 }
183
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200184 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);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200192
193 ++next_read_index_;
194 if (next_read_index_ == queue_.size()) {
195 next_read_index_ = 0;
196 }
197
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198 RTC_DCHECK_LT(next_read_index_, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200199
200 return true;
201 }
202
Artem Titov728a0ee2019-08-20 13:36:35 +0200203 // 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.
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
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200213 private:
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200214 // 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.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200216 bool VerifyQueueSlots() {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200217 for (const auto& v : queue_) {
218 RTC_DCHECK(queue_item_verifier_(v));
219 }
220 return true;
221 }
222
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200223 // TODO(peah): Change this to use std::function() once we can use C++11 std
224 // lib.
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200225 QueueItemVerifier queue_item_verifier_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200226
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200227 // Only accessed by the single producer.
228 size_t next_write_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200229
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200230 // Only accessed by the single consumer.
231 size_t next_read_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200233 // 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;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200243};
244
245} // namespace webrtc
peah48407f72015-11-09 05:24:50 -0800246
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200247#endif // RTC_BASE_SWAP_QUEUE_H_