1 /*
2 * Copyright 2018 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
11 #include "rtc_base/task_queue_stdlib.h"
12
13 #include <string.h>
14
15 #include <algorithm>
16 #include <map>
17 #include <memory>
18 #include <queue>
19 #include <utility>
20
21 #include "absl/functional/any_invocable.h"
22 #include "absl/strings/string_view.h"
23 #include "api/task_queue/task_queue_base.h"
24 #include "api/units/time_delta.h"
25 #include "rtc_base/checks.h"
26 #include "rtc_base/event.h"
27 #include "rtc_base/logging.h"
28 #include "rtc_base/numerics/divide_round.h"
29 #include "rtc_base/platform_thread.h"
30 #include "rtc_base/synchronization/mutex.h"
31 #include "rtc_base/thread_annotations.h"
32 #include "rtc_base/time_utils.h"
33
34 namespace webrtc {
35 namespace {
36
TaskQueuePriorityToThreadPriority(TaskQueueFactory::Priority priority)37 rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
38 TaskQueueFactory::Priority priority) {
39 switch (priority) {
40 case TaskQueueFactory::Priority::HIGH:
41 return rtc::ThreadPriority::kRealtime;
42 case TaskQueueFactory::Priority::LOW:
43 return rtc::ThreadPriority::kLow;
44 case TaskQueueFactory::Priority::NORMAL:
45 return rtc::ThreadPriority::kNormal;
46 }
47 }
48
49 class TaskQueueStdlib final : public TaskQueueBase {
50 public:
51 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
52 ~TaskQueueStdlib() override = default;
53
54 void Delete() override;
55 void PostTask(absl::AnyInvocable<void() &&> task) override;
56 void PostDelayedTask(absl::AnyInvocable<void() &&> task,
57 TimeDelta delay) override;
58 void PostDelayedHighPrecisionTask(absl::AnyInvocable<void() &&> task,
59 TimeDelta delay) override;
60
61 private:
62 using OrderId = uint64_t;
63
64 struct DelayedEntryTimeout {
65 // TODO(bugs.webrtc.org/13756): Migrate to Timestamp.
66 int64_t next_fire_at_us{};
67 OrderId order{};
68
operator <webrtc::__anond8aa200a0111::TaskQueueStdlib::DelayedEntryTimeout69 bool operator<(const DelayedEntryTimeout& o) const {
70 return std::tie(next_fire_at_us, order) <
71 std::tie(o.next_fire_at_us, o.order);
72 }
73 };
74
75 struct NextTask {
76 bool final_task = false;
77 absl::AnyInvocable<void() &&> run_task;
78 TimeDelta sleep_time = rtc::Event::kForever;
79 };
80
81 static rtc::PlatformThread InitializeThread(TaskQueueStdlib* me,
82 absl::string_view queue_name,
83 rtc::ThreadPriority priority);
84
85 NextTask GetNextTask();
86
87 void ProcessTasks();
88
89 void NotifyWake();
90
91 // Signaled whenever a new task is pending.
92 rtc::Event flag_notify_;
93
94 Mutex pending_lock_;
95
96 // Indicates if the worker thread needs to shutdown now.
97 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_) = false;
98
99 // Holds the next order to use for the next task to be
100 // put into one of the pending queues.
101 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_) = 0;
102
103 // The list of all pending tasks that need to be processed in the
104 // FIFO queue ordering on the worker thread.
105 std::queue<std::pair<OrderId, absl::AnyInvocable<void() &&>>> pending_queue_
106 RTC_GUARDED_BY(pending_lock_);
107
108 // The list of all pending tasks that need to be processed at a future
109 // time based upon a delay. On the off change the delayed task should
110 // happen at exactly the same time interval as another task then the
111 // task is processed based on FIFO ordering. std::priority_queue was
112 // considered but rejected due to its inability to extract the
113 // move-only value out of the queue without the presence of a hack.
114 std::map<DelayedEntryTimeout, absl::AnyInvocable<void() &&>> delayed_queue_
115 RTC_GUARDED_BY(pending_lock_);
116
117 // Contains the active worker thread assigned to processing
118 // tasks (including delayed tasks).
119 // Placing this last ensures the thread doesn't touch uninitialized attributes
120 // throughout it's lifetime.
121 rtc::PlatformThread thread_;
122 };
123
TaskQueueStdlib(absl::string_view queue_name,rtc::ThreadPriority priority)124 TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
125 rtc::ThreadPriority priority)
126 : flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
127 thread_(InitializeThread(this, queue_name, priority)) {}
128
129 // static
InitializeThread(TaskQueueStdlib * me,absl::string_view queue_name,rtc::ThreadPriority priority)130 rtc::PlatformThread TaskQueueStdlib::InitializeThread(
131 TaskQueueStdlib* me,
132 absl::string_view queue_name,
133 rtc::ThreadPriority priority) {
134 rtc::Event started;
135 auto thread = rtc::PlatformThread::SpawnJoinable(
136 [&started, me] {
137 CurrentTaskQueueSetter set_current(me);
138 started.Set();
139 me->ProcessTasks();
140 },
141 queue_name, rtc::ThreadAttributes().SetPriority(priority));
142 started.Wait(rtc::Event::kForever);
143 return thread;
144 }
145
Delete()146 void TaskQueueStdlib::Delete() {
147 RTC_DCHECK(!IsCurrent());
148
149 {
150 MutexLock lock(&pending_lock_);
151 thread_should_quit_ = true;
152 }
153
154 NotifyWake();
155
156 delete this;
157 }
158
PostTask(absl::AnyInvocable<void ()&&> task)159 void TaskQueueStdlib::PostTask(absl::AnyInvocable<void() &&> task) {
160 {
161 MutexLock lock(&pending_lock_);
162 pending_queue_.push(
163 std::make_pair(++thread_posting_order_, std::move(task)));
164 }
165
166 NotifyWake();
167 }
168
PostDelayedTask(absl::AnyInvocable<void ()&&> task,TimeDelta delay)169 void TaskQueueStdlib::PostDelayedTask(absl::AnyInvocable<void() &&> task,
170 TimeDelta delay) {
171 DelayedEntryTimeout delayed_entry;
172 delayed_entry.next_fire_at_us = rtc::TimeMicros() + delay.us();
173
174 {
175 MutexLock lock(&pending_lock_);
176 delayed_entry.order = ++thread_posting_order_;
177 delayed_queue_[delayed_entry] = std::move(task);
178 }
179
180 NotifyWake();
181 }
182
PostDelayedHighPrecisionTask(absl::AnyInvocable<void ()&&> task,TimeDelta delay)183 void TaskQueueStdlib::PostDelayedHighPrecisionTask(
184 absl::AnyInvocable<void() &&> task,
185 TimeDelta delay) {
186 PostDelayedTask(std::move(task), delay);
187 }
188
GetNextTask()189 TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
190 NextTask result;
191
192 const int64_t tick_us = rtc::TimeMicros();
193
194 MutexLock lock(&pending_lock_);
195
196 if (thread_should_quit_) {
197 result.final_task = true;
198 return result;
199 }
200
201 if (delayed_queue_.size() > 0) {
202 auto delayed_entry = delayed_queue_.begin();
203 const auto& delay_info = delayed_entry->first;
204 auto& delay_run = delayed_entry->second;
205 if (tick_us >= delay_info.next_fire_at_us) {
206 if (pending_queue_.size() > 0) {
207 auto& entry = pending_queue_.front();
208 auto& entry_order = entry.first;
209 auto& entry_run = entry.second;
210 if (entry_order < delay_info.order) {
211 result.run_task = std::move(entry_run);
212 pending_queue_.pop();
213 return result;
214 }
215 }
216
217 result.run_task = std::move(delay_run);
218 delayed_queue_.erase(delayed_entry);
219 return result;
220 }
221
222 result.sleep_time = TimeDelta::Millis(
223 DivideRoundUp(delay_info.next_fire_at_us - tick_us, 1'000));
224 }
225
226 if (pending_queue_.size() > 0) {
227 auto& entry = pending_queue_.front();
228 result.run_task = std::move(entry.second);
229 pending_queue_.pop();
230 }
231
232 return result;
233 }
234
ProcessTasks()235 void TaskQueueStdlib::ProcessTasks() {
236 while (true) {
237 auto task = GetNextTask();
238
239 if (task.final_task)
240 break;
241
242 if (task.run_task) {
243 // process entry immediately then try again
244 std::move(task.run_task)();
245
246 // Attempt to run more tasks before going to sleep.
247 continue;
248 }
249
250 flag_notify_.Wait(task.sleep_time);
251 }
252 }
253
NotifyWake()254 void TaskQueueStdlib::NotifyWake() {
255 // The queue holds pending tasks to complete. Either tasks are to be
256 // executed immediately or tasks are to be run at some future delayed time.
257 // For immediate tasks the task queue's thread is busy running the task and
258 // the thread will not be waiting on the flag_notify_ event. If no immediate
259 // tasks are available but a delayed task is pending then the thread will be
260 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
261 // to run. If no immediate or pending tasks are available, the thread will
262 // wait on flag_notify_ until signaled that a task has been added (or the
263 // thread to be told to shutdown).
264
265 // In all cases, when a new immediate task, delayed task, or request to
266 // shutdown the thread is added the flag_notify_ is signaled after. If the
267 // thread was waiting then the thread will wake up immediately and re-assess
268 // what task needs to be run next (i.e. run a task now, wait for the nearest
269 // timed delayed task, or shutdown the thread). If the thread was not waiting
270 // then the thread will remained signaled to wake up the next time any
271 // attempt to wait on the flag_notify_ event occurs.
272
273 // Any immediate or delayed pending task (or request to shutdown the thread)
274 // must always be added to the queue prior to signaling flag_notify_ to wake
275 // up the possibly sleeping thread. This prevents a race condition where the
276 // thread is notified to wake up but the task queue's thread finds nothing to
277 // do so it waits once again to be signaled where such a signal may never
278 // happen.
279 flag_notify_.Set();
280 }
281
282 class TaskQueueStdlibFactory final : public TaskQueueFactory {
283 public:
CreateTaskQueue(absl::string_view name,Priority priority) const284 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
285 absl::string_view name,
286 Priority priority) const override {
287 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
288 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
289 }
290 };
291
292 } // namespace
293
CreateTaskQueueStdlibFactory()294 std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
295 return std::make_unique<TaskQueueStdlibFactory>();
296 }
297
298 } // namespace webrtc
299