blob: 9eac49a933f6cff5f73d94fec3b6b04744c0e85d [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"
Danil Chapovalov4319b162021-01-14 15:02:22 +000021#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.
Danil Chapovalov4319b162021-01-14 15:02:22 +0000130 bool Insert(T* input) RTC_WARN_UNUSED_RESULT {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200131 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
Per Åhgrenc8b31832020-09-16 15:26:17 +0200144 using std::swap;
145 swap(*input, queue_[next_write_index_]);
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200146
147 // Increment the value of num_elements_ to account for the inserted element.
148 // Release memory ordering prevents the reads and writes to
149 // queue_[next_write_index_] to be reordered to after the increment. (Once
150 // the increment has finished, Remove() might start accessing that element.)
151 const size_t old_num_elements = std::atomic_fetch_add_explicit(
152 &num_elements_, size_t{1}, std::memory_order_release);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200153
154 ++next_write_index_;
155 if (next_write_index_ == queue_.size()) {
156 next_write_index_ = 0;
157 }
158
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200159 RTC_DCHECK_LT(next_write_index_, queue_.size());
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200160 RTC_DCHECK_LT(old_num_elements, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200161
162 return true;
163 }
164
165 // Removes the frontmost "full" T from the queue by swapping it with
166 // the "empty" T in *output.
167 // Returns true if an item could be removed or false if not (the queue was
168 // empty). When specified, The T given in *output must pass the ItemVerifier()
169 // test and the contents of *output after the call are then also guaranteed to
170 // pass the ItemVerifier() test.
Danil Chapovalov4319b162021-01-14 15:02:22 +0000171 bool Remove(T* output) RTC_WARN_UNUSED_RESULT {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172 RTC_DCHECK(output);
173
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200174 RTC_DCHECK(queue_item_verifier_(*output));
175
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200176 // Load the value of num_elements_. Acquire memory ordering prevents reads
177 // and writes to queue_[next_read_index_] to be reordered to before the
178 // load. (That element might be accessed by a concurrent call to Insert()
179 // until the load finishes.)
180 if (std::atomic_load_explicit(&num_elements_, std::memory_order_acquire) ==
181 0) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200182 return false;
183 }
184
Per Åhgrenc8b31832020-09-16 15:26:17 +0200185 using std::swap;
186 swap(*output, queue_[next_read_index_]);
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200187
188 // Decrement the value of num_elements_ to account for the removed element.
189 // Release memory ordering prevents the reads and writes to
190 // queue_[next_write_index_] to be reordered to after the decrement. (Once
191 // the decrement has finished, Insert() might start accessing that element.)
192 std::atomic_fetch_sub_explicit(&num_elements_, size_t{1},
193 std::memory_order_release);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200194
195 ++next_read_index_;
196 if (next_read_index_ == queue_.size()) {
197 next_read_index_ = 0;
198 }
199
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200200 RTC_DCHECK_LT(next_read_index_, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200201
202 return true;
203 }
204
Artem Titov728a0ee2019-08-20 13:36:35 +0200205 // Returns the current number of elements in the queue. Since elements may be
206 // concurrently added to the queue, the caller must treat this as a lower
207 // bound, not an exact count.
208 // May only be called by the consumer.
209 size_t SizeAtLeast() const {
210 // Acquire memory ordering ensures that we wait for the producer to finish
211 // inserting any element in progress.
212 return std::atomic_load_explicit(&num_elements_, std::memory_order_acquire);
213 }
214
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215 private:
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200216 // Verify that the queue slots complies with the ItemVerifier test. This
217 // function is not thread-safe and can only be used in the constructors.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200218 bool VerifyQueueSlots() {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200219 for (const auto& v : queue_) {
220 RTC_DCHECK(queue_item_verifier_(v));
221 }
222 return true;
223 }
224
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200225 // TODO(peah): Change this to use std::function() once we can use C++11 std
226 // lib.
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200227 QueueItemVerifier queue_item_verifier_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200228
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200229 // Only accessed by the single producer.
230 size_t next_write_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200231
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200232 // Only accessed by the single consumer.
233 size_t next_read_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200234
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200235 // Accessed by both the producer and the consumer and used for synchronization
236 // between them.
237 std::atomic<size_t> num_elements_{0};
238
239 // The elements of the queue are acced by both the producer and the consumer,
240 // mediated by num_elements_. queue_.size() is constant.
241 std::vector<T> queue_;
242
243 SwapQueue(const SwapQueue&) = delete;
244 SwapQueue& operator=(const SwapQueue&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200245};
246
247} // namespace webrtc
peah48407f72015-11-09 05:24:50 -0800248
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200249#endif // RTC_BASE_SWAP_QUEUE_H_