C/C++ API Reference
Loading...
Searching...
No Matches
work_queue.h
1// Copyright 2021 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15#pragma once
16
17#include <cstdint>
18#include <mutex>
19
20#include "pw_assert/assert.h"
21#include "pw_containers/inline_queue.h"
22#include "pw_function/function.h"
23#include "pw_metric/metric.h"
24#include "pw_status/status.h"
25#include "pw_sync/interrupt_spin_lock.h"
26#include "pw_sync/lock_annotations.h"
27#include "pw_sync/thread_notification.h"
28#include "pw_thread/thread_core.h"
29
31namespace pw::work_queue {
32
34
51template <typename WorkItem>
52class CustomWorkQueue : public thread::ThreadCore {
53 public:
60 pw::Function<void(WorkItem&)>&& fn)
61 : stop_requested_(false), queue_(queue), fn_(std::move(fn)) {
62 min_queue_remaining_.Set(static_cast<uint32_t>(queue.capacity()));
63 }
64
75 Status PushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
76 return InternalPushWork(std::move(work_item));
77 }
78
92 void CheckPushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
93 PW_ASSERT_OK(InternalPushWork(std::move(work_item)),
94 "Failed to push work item into the work queue");
95 }
96 void CheckPushWork(WorkItem& work_item) PW_LOCKS_EXCLUDED(lock_) {
97 PW_ASSERT_OK(InternalPushWork(std::move(work_item)),
98 "Failed to push work item into the work queue");
99 }
100
108 {
109 std::lock_guard lock(lock_);
110 stop_requested_ = true;
111 } // Release lock before calling .release() on the semaphore.
112 work_notification_.release();
113 }
114
119 void Clear() PW_LOCKS_EXCLUDED(lock_) {
120 std::lock_guard lock(lock_);
121 queue_.clear();
122 }
123
124 private:
125 void Run() override PW_LOCKS_EXCLUDED(lock_) {
126 while (true) {
127 work_notification_.acquire();
128
129 // Drain the work queue.
130 bool stop_requested;
131 bool work_remaining;
132 do {
133 std::optional<WorkItem> possible_work_item;
134 {
135 std::lock_guard lock(lock_);
136 if (!queue_.empty()) {
137 possible_work_item.emplace(std::move(queue_.front()));
138 queue_.pop();
139 }
140 work_remaining = !queue_.empty();
141 stop_requested = stop_requested_;
142 }
143 if (!possible_work_item.has_value()) {
144 continue; // No work item to process.
145 }
146 WorkItem& work_item = possible_work_item.value();
147 fn_(work_item);
148 } while (work_remaining);
149
150 // Queue was drained, return if we've been requested to stop.
151 if (stop_requested) {
152 return;
153 }
154 }
155 }
156
157 Status InternalPushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
158 {
159 std::lock_guard lock(lock_);
160
161 if (stop_requested_) {
162 // Entries are not permitted to be enqueued once stop has been
163 // requested.
165 }
166
167 if (queue_.full()) {
169 }
170
171 queue_.emplace(std::move(work_item));
172
173 // Update the watermarks for the queue.
174 const uint32_t queue_entries = queue_.size();
175 if (queue_entries > max_queue_used_.value()) {
176 max_queue_used_.Set(queue_entries);
177 }
178 const uint32_t queue_remaining = queue_.capacity() - queue_entries;
179 if (queue_remaining < min_queue_remaining_.value()) {
180 min_queue_remaining_.Set(queue_entries);
181 }
182 } // Release lock before calling .release() on the semaphore.
183 work_notification_.release();
184 return OkStatus();
185 }
186 sync::InterruptSpinLock lock_;
187 bool stop_requested_ PW_GUARDED_BY(lock_);
188 InlineQueue<WorkItem>& queue_ PW_GUARDED_BY(lock_);
189 sync::ThreadNotification work_notification_;
190 pw::Function<void(WorkItem&)> fn_;
191
192 // TODO(ewout): The group and/or its name token should be passed as a ctor
193 // arg instead. Depending on the approach here the group should be exposed
194 // While doing this evaluate whether perhaps we should instead construct
195 // TypedMetric<uint32_t>s directly, avoiding the macro usage given the
196 // min_queue_remaining_ initial value requires dependency injection.
197 // And lastly when the restructure is finalized add unit tests to ensure these
198 // metrics work as intended.
199 PW_METRIC_GROUP(metrics_, "pw::work_queue::WorkQueue");
200 PW_METRIC(metrics_, max_queue_used_, "max_queue_used", 0u);
201 PW_METRIC(metrics_, min_queue_remaining_, "min_queue_remaining", 0u);
202};
203
208class WorkQueue : public CustomWorkQueue<Closure> {
209 public:
212 : CustomWorkQueue(queue, [](Closure& fn) { fn(); }) {}
213};
214
216
217namespace internal {
218
219// Storage base class for the WorkQueueWithBuffer classes. The queue must be a
220// base class instead of a member so the queue is initialized before it is
221// passed to the CustomWorkQueue base.
222template <typename WorkItem, size_t kWorkQueueEntries>
223struct Storage {
225};
226
227} // namespace internal
228
230
236template <size_t kWorkQueueEntries, typename WorkItem>
238 : private internal::Storage<WorkItem, kWorkQueueEntries>,
239 public CustomWorkQueue<WorkItem> {
240 public:
242 constexpr CustomWorkQueueWithBuffer(pw::Function<void(WorkItem&)>&& fn)
243 : CustomWorkQueue<WorkItem>(
244 internal::Storage<WorkItem, kWorkQueueEntries>::queue,
245 std::move(fn)) {}
246};
247
255template <size_t kWorkQueueEntries>
257 : private internal::Storage<Closure, kWorkQueueEntries>,
258 public WorkQueue {
259 public:
260 constexpr WorkQueueWithBuffer()
262};
263
264} // namespace pw::work_queue
Definition: inline_queue.h:55
Definition: status.h:120
static constexpr Status FailedPrecondition()
Definition: status.h:243
static constexpr Status ResourceExhausted()
Definition: status.h:230
Definition: work_queue.h:52
Definition: work_queue.h:239
Definition: work_queue.h:208
Definition: work_queue.h:258
fit::function_impl< function_internal::config::kInlineCallableSize, !function_internal::config::kEnableDynamicAllocation, FunctionType, PW_FUNCTION_DEFAULT_ALLOCATOR_TYPE > Function
Definition: function.h:73
Function< void()> Closure
void-returning pw::Function that takes no arguments.
Definition: function.h:111
constexpr Status OkStatus()
Definition: status.h:450
#define PW_GUARDED_BY(x)
Definition: lock_annotations.h:60
#define PW_LOCKS_EXCLUDED(...)
Definition: lock_annotations.h:178
void Clear()
Definition: work_queue.h:119
void CheckPushWork(WorkItem &&work_item)
Definition: work_queue.h:92
void RequestStop()
Definition: work_queue.h:107
Status PushWork(WorkItem &&work_item)
Definition: work_queue.h:75
CustomWorkQueue(InlineQueue< WorkItem > &queue, pw::Function< void(WorkItem &)> &&fn)
Definition: work_queue.h:59
WorkQueue(InlineQueue< Closure > &queue)
Definition: work_queue.h:211
constexpr CustomWorkQueueWithBuffer(pw::Function< void(WorkItem &)> &&fn)
Definition: work_queue.h:242
Work queue library for threads and interrupts.
Definition: work_queue.h:31
Definition: work_queue.h:223