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
82 Status PushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
83 return InternalPushWork(std::move(work_item));
84 }
85
99 void CheckPushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
100 PW_ASSERT_OK(InternalPushWork(std::move(work_item)),
101 "Failed to push work item into the work queue");
102 }
103 void CheckPushWork(WorkItem& work_item) PW_LOCKS_EXCLUDED(lock_) {
104 PW_ASSERT_OK(InternalPushWork(std::move(work_item)),
105 "Failed to push work item into the work queue");
106 }
107
115 {
116 std::lock_guard lock(lock_);
117 stop_requested_ = true;
118 } // Release lock before calling .release() on the semaphore.
119 work_notification_.release();
120 }
121
122 private:
123 void Run() override PW_LOCKS_EXCLUDED(lock_) {
124 while (true) {
125 work_notification_.acquire();
126
127 // Drain the work queue.
128 bool stop_requested;
129 bool work_remaining;
130 do {
131 std::optional<WorkItem> possible_work_item;
132 {
133 std::lock_guard lock(lock_);
134 if (!queue_.empty()) {
135 possible_work_item.emplace(std::move(queue_.front()));
136 queue_.pop();
137 }
138 work_remaining = !queue_.empty();
139 stop_requested = stop_requested_;
140 }
141 if (!possible_work_item.has_value()) {
142 continue; // No work item to process.
143 }
144 WorkItem& work_item = possible_work_item.value();
145 fn_(work_item);
146 } while (work_remaining);
147
148 // Queue was drained, return if we've been requested to stop.
149 if (stop_requested) {
150 return;
151 }
152 }
153 }
154
155 Status InternalPushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
156 {
157 std::lock_guard lock(lock_);
158
159 if (stop_requested_) {
160 // Entries are not permitted to be enqueued once stop has been
161 // requested.
163 }
164
165 if (queue_.full()) {
167 }
168
169 queue_.emplace(std::move(work_item));
170
171 // Update the watermarks for the queue.
172 const uint32_t queue_entries = queue_.size();
173 if (queue_entries > max_queue_used_.value()) {
174 max_queue_used_.Set(queue_entries);
175 }
176 const uint32_t queue_remaining = queue_.capacity() - queue_entries;
177 if (queue_remaining < min_queue_remaining_.value()) {
178 min_queue_remaining_.Set(queue_entries);
179 }
180 } // Release lock before calling .release() on the semaphore.
181 work_notification_.release();
182 return OkStatus();
183 }
184 sync::InterruptSpinLock lock_;
185 bool stop_requested_ PW_GUARDED_BY(lock_);
186 InlineQueue<WorkItem>& queue_ PW_GUARDED_BY(lock_);
187 sync::ThreadNotification work_notification_;
188 pw::Function<void(WorkItem&)> fn_;
189
190 // TODO(ewout): The group and/or its name token should be passed as a ctor
191 // arg instead. Depending on the approach here the group should be exposed
192 // While doing this evaluate whether perhaps we should instead construct
193 // TypedMetric<uint32_t>s directly, avoiding the macro usage given the
194 // min_queue_remaining_ initial value requires dependency injection.
195 // And lastly when the restructure is finalized add unit tests to ensure these
196 // metrics work as intended.
197 PW_METRIC_GROUP(metrics_, "pw::work_queue::WorkQueue");
198 PW_METRIC(metrics_, max_queue_used_, "max_queue_used", 0u);
199 PW_METRIC(metrics_, min_queue_remaining_, "min_queue_remaining", 0u);
200};
201
206class WorkQueue : public CustomWorkQueue<Closure> {
207 public:
210 : CustomWorkQueue(queue, [](Closure& fn) { fn(); }) {}
211};
212
214
215namespace internal {
216
217// Storage base class for the WorkQueueWithBuffer classes. The queue must be a
218// base class instead of a member so the queue is initialized before it is
219// passed to the CustomWorkQueue base.
220template <typename WorkItem, size_t kWorkQueueEntries>
221struct Storage {
223};
224
225} // namespace internal
226
228
234template <size_t kWorkQueueEntries, typename WorkItem>
236 : private internal::Storage<WorkItem, kWorkQueueEntries>,
237 public CustomWorkQueue<WorkItem> {
238 public:
240 constexpr CustomWorkQueueWithBuffer(pw::Function<void(WorkItem&)>&& fn)
241 : CustomWorkQueue<WorkItem>(
242 internal::Storage<WorkItem, kWorkQueueEntries>::queue,
243 std::move(fn)) {}
244};
245
253template <size_t kWorkQueueEntries>
255 : private internal::Storage<Closure, kWorkQueueEntries>,
256 public WorkQueue {
257 public:
258 constexpr WorkQueueWithBuffer()
260};
261
262} // namespace pw::work_queue
Definition: inline_queue.h:55
Definition: status.h:109
static constexpr Status FailedPrecondition()
System isn’t in the required state; e.g. deleting a non-empty directory.
Definition: status.h:162
static constexpr Status ResourceExhausted()
Definition: status.h:157
Definition: work_queue.h:52
Definition: work_queue.h:237
Definition: work_queue.h:206
Definition: work_queue.h:256
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:297
#define PW_GUARDED_BY(x)
Definition: lock_annotations.h:60
#define PW_LOCKS_EXCLUDED(...)
Definition: lock_annotations.h:176
void CheckPushWork(WorkItem &&work_item)
Definition: work_queue.h:99
void RequestStop()
Definition: work_queue.h:114
Status PushWork(WorkItem &&work_item)
Definition: work_queue.h:82
CustomWorkQueue(InlineQueue< WorkItem > &queue, pw::Function< void(WorkItem &)> &&fn)
Definition: work_queue.h:59
WorkQueue(InlineQueue< Closure > &queue)
Definition: work_queue.h:209
constexpr CustomWorkQueueWithBuffer(pw::Function< void(WorkItem &)> &&fn)
Definition: work_queue.h:240
Work queue library for threads and interrupts.
Definition: work_queue.h:31
Definition: work_queue.h:221