blob: 8dd2a286dd6bf9df987564adedc4f9ad9e168336 [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>
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +020015#include <atomic>
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020016#include <utility>
17#include <vector>
peah48407f72015-11-09 05:24:50 -080018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "rtc_base/checks.h"
Niels Möllera12c42a2018-07-25 16:05:48 +020020#include "rtc_base/system/unused.h"
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020021
22namespace webrtc {
23
24namespace internal {
25
26// (Internal; please don't use outside this file.)
27template <typename T>
28bool NoopSwapQueueItemVerifierFunction(const T&) {
29 return true;
30}
31
32} // namespace internal
33
34// Functor to use when supplying a verifier function for the queue.
35template <typename T,
36 bool (*QueueItemVerifierFunction)(const T&) =
37 internal::NoopSwapQueueItemVerifierFunction>
38class SwapQueueItemVerifier {
39 public:
40 bool operator()(const T& t) const { return QueueItemVerifierFunction(t); }
41};
42
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +020043// This class is a fixed-size queue. A single producer calls Insert() to insert
44// an element of type T at the back of the queue, and a single consumer calls
45// Remove() to remove an element from the front of the queue. It's safe for the
46// producer and the consumer to access the queue concurrently, from different
47// threads.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020048//
49// To avoid the construction, copying, and destruction of Ts that a naive
50// queue implementation would require, for each "full" T passed from
51// producer to consumer, SwapQueue<T> passes an "empty" T in the other
52// direction (an "empty" T is one that contains nothing of value for the
53// consumer). This bidirectional movement is implemented with swap().
54//
55// // Create queue:
56// Bottle proto(568); // Prepare an empty Bottle. Heap allocates space for
57// // 568 ml.
58// SwapQueue<Bottle> q(N, proto); // Init queue with N copies of proto.
59// // Each copy allocates on the heap.
60// // Producer pseudo-code:
61// Bottle b(568); // Prepare an empty Bottle. Heap allocates space for 568 ml.
62// loop {
63// b.Fill(amount); // Where amount <= 568 ml.
64// q.Insert(&b); // Swap our full Bottle for an empty one from q.
65// }
66//
67// // Consumer pseudo-code:
68// Bottle b(568); // Prepare an empty Bottle. Heap allocates space for 568 ml.
69// loop {
70// q.Remove(&b); // Swap our empty Bottle for the next-in-line full Bottle.
71// Drink(&b);
72// }
73//
74// For a well-behaved Bottle class, there are no allocations in the
75// producer, since it just fills an empty Bottle that's already large
76// enough; no deallocations in the consumer, since it returns each empty
77// Bottle to the queue after having drunk it; and no copies along the
78// way, since the queue uses swap() everywhere to move full Bottles in
79// one direction and empty ones in the other.
80template <typename T, typename QueueItemVerifier = SwapQueueItemVerifier<T>>
81class SwapQueue {
82 public:
83 // Creates a queue of size size and fills it with default constructed Ts.
84 explicit SwapQueue(size_t size) : queue_(size) {
85 RTC_DCHECK(VerifyQueueSlots());
86 }
87
88 // Same as above and accepts an item verification functor.
89 SwapQueue(size_t size, const QueueItemVerifier& queue_item_verifier)
90 : queue_item_verifier_(queue_item_verifier), queue_(size) {
91 RTC_DCHECK(VerifyQueueSlots());
92 }
93
94 // Creates a queue of size size and fills it with copies of prototype.
95 SwapQueue(size_t size, const T& prototype) : queue_(size, prototype) {
96 RTC_DCHECK(VerifyQueueSlots());
97 }
98
99 // Same as above and accepts an item verification functor.
100 SwapQueue(size_t size,
101 const T& prototype,
102 const QueueItemVerifier& queue_item_verifier)
103 : queue_item_verifier_(queue_item_verifier), queue_(size, prototype) {
104 RTC_DCHECK(VerifyQueueSlots());
105 }
106
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200107 // Resets the queue to have zero content while maintaining the queue size.
108 // Just like Remove(), this can only be called (safely) from the
109 // consumer.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200110 void Clear() {
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200111 // Drop all non-empty elements by resetting num_elements_ and incrementing
112 // next_read_index_ by the previous value of num_elements_. Relaxed memory
113 // ordering is sufficient since the dropped elements are not accessed.
114 next_read_index_ += std::atomic_exchange_explicit(
115 &num_elements_, size_t{0}, std::memory_order_relaxed);
116 if (next_read_index_ >= queue_.size()) {
117 next_read_index_ -= queue_.size();
118 }
119
120 RTC_DCHECK_LT(next_read_index_, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200121 }
122
123 // Inserts a "full" T at the back of the queue by swapping *input with an
124 // "empty" T from the queue.
125 // Returns true if the item was inserted or false if not (the queue was full).
126 // When specified, the T given in *input must pass the ItemVerifier() test.
127 // The contents of *input after the call are then also guaranteed to pass the
128 // ItemVerifier() test.
129 bool Insert(T* input) RTC_WARN_UNUSED_RESULT {
130 RTC_DCHECK(input);
131
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200132 RTC_DCHECK(queue_item_verifier_(*input));
133
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200134 // Load the value of num_elements_. Acquire memory ordering prevents reads
135 // and writes to queue_[next_write_index_] to be reordered to before the
136 // load. (That element might be accessed by a concurrent call to Remove()
137 // until the load finishes.)
138 if (std::atomic_load_explicit(&num_elements_, std::memory_order_acquire) ==
139 queue_.size()) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200140 return false;
141 }
142
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200143 std::swap(*input, queue_[next_write_index_]);
144
145 // Increment the value of num_elements_ to account for the inserted element.
146 // Release memory ordering prevents the reads and writes to
147 // queue_[next_write_index_] to be reordered to after the increment. (Once
148 // the increment has finished, Remove() might start accessing that element.)
149 const size_t old_num_elements = std::atomic_fetch_add_explicit(
150 &num_elements_, size_t{1}, std::memory_order_release);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151
152 ++next_write_index_;
153 if (next_write_index_ == queue_.size()) {
154 next_write_index_ = 0;
155 }
156
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200157 RTC_DCHECK_LT(next_write_index_, queue_.size());
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200158 RTC_DCHECK_LT(old_num_elements, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200159
160 return true;
161 }
162
163 // Removes the frontmost "full" T from the queue by swapping it with
164 // the "empty" T in *output.
165 // Returns true if an item could be removed or false if not (the queue was
166 // empty). When specified, The T given in *output must pass the ItemVerifier()
167 // test and the contents of *output after the call are then also guaranteed to
168 // pass the ItemVerifier() test.
169 bool Remove(T* output) RTC_WARN_UNUSED_RESULT {
170 RTC_DCHECK(output);
171
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200172 RTC_DCHECK(queue_item_verifier_(*output));
173
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200174 // Load the value of num_elements_. Acquire memory ordering prevents reads
175 // and writes to queue_[next_read_index_] to be reordered to before the
176 // load. (That element might be accessed by a concurrent call to Insert()
177 // until the load finishes.)
178 if (std::atomic_load_explicit(&num_elements_, std::memory_order_acquire) ==
179 0) {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200180 return false;
181 }
182
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200183 std::swap(*output, queue_[next_read_index_]);
184
185 // Decrement the value of num_elements_ to account for the removed element.
186 // Release memory ordering prevents the reads and writes to
187 // queue_[next_write_index_] to be reordered to after the decrement. (Once
188 // the decrement has finished, Insert() might start accessing that element.)
189 std::atomic_fetch_sub_explicit(&num_elements_, size_t{1},
190 std::memory_order_release);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191
192 ++next_read_index_;
193 if (next_read_index_ == queue_.size()) {
194 next_read_index_ = 0;
195 }
196
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200197 RTC_DCHECK_LT(next_read_index_, queue_.size());
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200198
199 return true;
200 }
201
202 private:
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200203 // Verify that the queue slots complies with the ItemVerifier test. This
204 // function is not thread-safe and can only be used in the constructors.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200205 bool VerifyQueueSlots() {
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200206 for (const auto& v : queue_) {
207 RTC_DCHECK(queue_item_verifier_(v));
208 }
209 return true;
210 }
211
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200212 // TODO(peah): Change this to use std::function() once we can use C++11 std
213 // lib.
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200214 QueueItemVerifier queue_item_verifier_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200215
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200216 // Only accessed by the single producer.
217 size_t next_write_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200218
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200219 // Only accessed by the single consumer.
220 size_t next_read_index_ = 0;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200221
Gustaf Ullberg4cd1c6a2019-06-03 13:09:08 +0200222 // Accessed by both the producer and the consumer and used for synchronization
223 // between them.
224 std::atomic<size_t> num_elements_{0};
225
226 // The elements of the queue are acced by both the producer and the consumer,
227 // mediated by num_elements_. queue_.size() is constant.
228 std::vector<T> queue_;
229
230 SwapQueue(const SwapQueue&) = delete;
231 SwapQueue& operator=(const SwapQueue&) = delete;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200232};
233
234} // namespace webrtc
peah48407f72015-11-09 05:24:50 -0800235
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200236#endif // RTC_BASE_SWAP_QUEUE_H_