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
115 private:
116 void Run() override PW_LOCKS_EXCLUDED(lock_) {
117 while (true) {
118 work_notification_.acquire();
119
120 // Drain the work queue.
121 bool stop_requested;
122 bool work_remaining;
123 do {
124 std::optional<WorkItem> possible_work_item;
125 {
126 std::lock_guard lock(lock_);
127 if (!queue_.empty()) {
128 possible_work_item.emplace(std::move(queue_.front()));
129 queue_.pop();
130 }
131 work_remaining = !queue_.empty();
132 stop_requested = stop_requested_;
133 }
134 if (!possible_work_item.has_value()) {
135 continue; // No work item to process.
136 }
137 WorkItem& work_item = possible_work_item.value();
138 fn_(work_item);
139 } while (work_remaining);
140
141 // Queue was drained, return if we've been requested to stop.
142 if (stop_requested) {
143 return;
144 }
145 }
146 }
147
148 Status InternalPushWork(WorkItem&& work_item) PW_LOCKS_EXCLUDED(lock_) {
149 {
150 std::lock_guard lock(lock_);
151
152 if (stop_requested_) {
153 // Entries are not permitted to be enqueued once stop has been
154 // requested.
156 }
157
158 if (queue_.full()) {
160 }
161
162 queue_.emplace(std::move(work_item));
163
164 // Update the watermarks for the queue.
165 const uint32_t queue_entries = queue_.size();
166 if (queue_entries > max_queue_used_.value()) {
167 max_queue_used_.Set(queue_entries);
168 }
169 const uint32_t queue_remaining = queue_.capacity() - queue_entries;
170 if (queue_remaining < min_queue_remaining_.value()) {
171 min_queue_remaining_.Set(queue_entries);
172 }
173 } // Release lock before calling .release() on the semaphore.
174 work_notification_.release();
175 return OkStatus();
176 }
177 sync::InterruptSpinLock lock_;
178 bool stop_requested_ PW_GUARDED_BY(lock_);
179 InlineQueue<WorkItem>& queue_ PW_GUARDED_BY(lock_);
180 sync::ThreadNotification work_notification_;
181 pw::Function<void(WorkItem&)> fn_;
182
183 // TODO(ewout): The group and/or its name token should be passed as a ctor
184 // arg instead. Depending on the approach here the group should be exposed
185 // While doing this evaluate whether perhaps we should instead construct
186 // TypedMetric<uint32_t>s directly, avoiding the macro usage given the
187 // min_queue_remaining_ initial value requires dependency injection.
188 // And lastly when the restructure is finalized add unit tests to ensure these
189 // metrics work as intended.
190 PW_METRIC_GROUP(metrics_, "pw::work_queue::WorkQueue");
191 PW_METRIC(metrics_, max_queue_used_, "max_queue_used", 0u);
192 PW_METRIC(metrics_, min_queue_remaining_, "min_queue_remaining", 0u);
193};
194
199class WorkQueue : public CustomWorkQueue<Closure> {
200 public:
203 : CustomWorkQueue(queue, [](Closure& fn) { fn(); }) {}
204};
205
207
208namespace internal {
209
210// Storage base class for the WorkQueueWithBuffer classes. The queue must be a
211// base class instead of a member so the queue is initialized before it is
212// passed to the CustomWorkQueue base.
213template <typename WorkItem, size_t kWorkQueueEntries>
214struct Storage {
216};
217
218} // namespace internal
219
221
227template <size_t kWorkQueueEntries, typename WorkItem>
229 : private internal::Storage<WorkItem, kWorkQueueEntries>,
230 public CustomWorkQueue<WorkItem> {
231 public:
233 constexpr CustomWorkQueueWithBuffer(pw::Function<void(WorkItem&)>&& fn)
234 : CustomWorkQueue<WorkItem>(
235 internal::Storage<WorkItem, kWorkQueueEntries>::queue,
236 std::move(fn)) {}
237};
238
246template <size_t kWorkQueueEntries>
248 : private internal::Storage<Closure, kWorkQueueEntries>,
249 public WorkQueue {
250 public:
251 constexpr WorkQueueWithBuffer()
253};
254
255} // 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:230
Definition: work_queue.h:199
Definition: work_queue.h:249
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:176
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:202
constexpr CustomWorkQueueWithBuffer(pw::Function< void(WorkItem &)> &&fn)
Definition: work_queue.h:233
Work queue library for threads and interrupts.
Definition: work_queue.h:31
Definition: work_queue.h:214