blob: f712cfa8c700fcf2259fd07c09645e028f2f84d6 [file] [log] [blame]
Robin Raymond22027b92018-11-23 09:07:50 -05001/*
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
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010011#include "rtc_base/task_queue_stdlib.h"
Robin Raymond22027b92018-11-23 09:07:50 -050012
13#include <string.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
Robin Raymond22027b92018-11-23 09:07:50 -050015#include <algorithm>
Robin Raymond22027b92018-11-23 09:07:50 -050016#include <map>
Mirko Bonadei317a1f02019-09-17 17:06:18 +020017#include <memory>
Robin Raymond22027b92018-11-23 09:07:50 -050018#include <queue>
19#include <utility>
20
Danil Chapovalovba570012022-07-19 18:36:31 +020021#include "absl/functional/any_invocable.h"
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010022#include "absl/strings/string_view.h"
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010023#include "api/task_queue/task_queue_base.h"
Danil Chapovalovba570012022-07-19 18:36:31 +020024#include "api/units/time_delta.h"
Robin Raymond22027b92018-11-23 09:07:50 -050025#include "rtc_base/checks.h"
Robin Raymond22027b92018-11-23 09:07:50 -050026#include "rtc_base/event.h"
27#include "rtc_base/logging.h"
Danil Chapovalovba570012022-07-19 18:36:31 +020028#include "rtc_base/numerics/divide_round.h"
Robin Raymond22027b92018-11-23 09:07:50 -050029#include "rtc_base/platform_thread.h"
Markus Handell18523c32020-07-08 17:55:58 +020030#include "rtc_base/synchronization/mutex.h"
Robin Raymond22027b92018-11-23 09:07:50 -050031#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 09:11:00 -080032#include "rtc_base/time_utils.h"
Robin Raymond22027b92018-11-23 09:07:50 -050033
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010034namespace webrtc {
Robin Raymond22027b92018-11-23 09:07:50 -050035namespace {
36
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010037rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
38 TaskQueueFactory::Priority priority) {
Robin Raymond22027b92018-11-23 09:07:50 -050039 switch (priority) {
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010040 case TaskQueueFactory::Priority::HIGH:
Markus Handellad5037b2021-05-07 15:02:36 +020041 return rtc::ThreadPriority::kRealtime;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010042 case TaskQueueFactory::Priority::LOW:
Markus Handellad5037b2021-05-07 15:02:36 +020043 return rtc::ThreadPriority::kLow;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010044 case TaskQueueFactory::Priority::NORMAL:
Markus Handellad5037b2021-05-07 15:02:36 +020045 return rtc::ThreadPriority::kNormal;
Robin Raymond22027b92018-11-23 09:07:50 -050046 }
Robin Raymond22027b92018-11-23 09:07:50 -050047}
48
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010049class TaskQueueStdlib final : public TaskQueueBase {
Robin Raymond22027b92018-11-23 09:07:50 -050050 public:
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010051 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
52 ~TaskQueueStdlib() override = default;
Robin Raymond22027b92018-11-23 09:07:50 -050053
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010054 void Delete() override;
Danil Chapovalovba570012022-07-19 18:36:31 +020055 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;
Robin Raymond22027b92018-11-23 09:07:50 -050060
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010061 private:
Robin Raymond22027b92018-11-23 09:07:50 -050062 using OrderId = uint64_t;
63
64 struct DelayedEntryTimeout {
Danil Chapovalovba570012022-07-19 18:36:31 +020065 int64_t next_fire_at_us{};
66 OrderId order{};
Robin Raymond22027b92018-11-23 09:07:50 -050067
68 bool operator<(const DelayedEntryTimeout& o) const {
Danil Chapovalovba570012022-07-19 18:36:31 +020069 return std::tie(next_fire_at_us, order) <
70 std::tie(o.next_fire_at_us, o.order);
Robin Raymond22027b92018-11-23 09:07:50 -050071 }
72 };
73
74 struct NextTask {
Danil Chapovalovba570012022-07-19 18:36:31 +020075 bool final_task = false;
76 absl::AnyInvocable<void() &&> run_task;
Markus Handell6df49b92022-08-17 13:39:59 +000077 // TODO(bugs.webrtc.org/14366): While transitioning to TimeDelta, WebRTC and
78 // Chromium has a different idea about what type rtc::Event::kForever is.
79 // Code can't assume rtc::Event::kForever is the same type as timed wait
80 // arguments.
81 // Change `sleep_time_ms` to be explicit type, default value
82 // `rtc::Event::kForever` once transition is complete.
83 absl::optional<int64_t> sleep_time_ms;
Robin Raymond22027b92018-11-23 09:07:50 -050084 };
85
Tommi76d9c182022-04-22 15:48:37 +020086 static rtc::PlatformThread InitializeThread(TaskQueueStdlib* me,
87 absl::string_view queue_name,
88 rtc::ThreadPriority priority);
89
Robin Raymond22027b92018-11-23 09:07:50 -050090 NextTask GetNextTask();
91
Robin Raymond22027b92018-11-23 09:07:50 -050092 void ProcessTasks();
93
94 void NotifyWake();
95
Robin Raymond22027b92018-11-23 09:07:50 -050096 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010097 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050098
Markus Handell18523c32020-07-08 17:55:58 +020099 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -0500100
101 // Indicates if the worker thread needs to shutdown now.
Tommi76d9c182022-04-22 15:48:37 +0200102 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_) = false;
Robin Raymond22027b92018-11-23 09:07:50 -0500103
104 // Holds the next order to use for the next task to be
105 // put into one of the pending queues.
Tommi76d9c182022-04-22 15:48:37 +0200106 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_) = 0;
Robin Raymond22027b92018-11-23 09:07:50 -0500107
108 // The list of all pending tasks that need to be processed in the
109 // FIFO queue ordering on the worker thread.
Danil Chapovalovba570012022-07-19 18:36:31 +0200110 std::queue<std::pair<OrderId, absl::AnyInvocable<void() &&>>> pending_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500111 RTC_GUARDED_BY(pending_lock_);
112
113 // The list of all pending tasks that need to be processed at a future
114 // time based upon a delay. On the off change the delayed task should
115 // happen at exactly the same time interval as another task then the
116 // task is processed based on FIFO ordering. std::priority_queue was
117 // considered but rejected due to its inability to extract the
Danil Chapovalovba570012022-07-19 18:36:31 +0200118 // move-only value out of the queue without the presence of a hack.
119 std::map<DelayedEntryTimeout, absl::AnyInvocable<void() &&>> delayed_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500120 RTC_GUARDED_BY(pending_lock_);
Markus Handell49cb4592021-06-22 10:02:26 +0200121
122 // Contains the active worker thread assigned to processing
123 // tasks (including delayed tasks).
124 // Placing this last ensures the thread doesn't touch uninitialized attributes
125 // throughout it's lifetime.
126 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 09:07:50 -0500127};
128
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100129TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
130 rtc::ThreadPriority priority)
Tommi76d9c182022-04-22 15:48:37 +0200131 : flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
132 thread_(InitializeThread(this, queue_name, priority)) {}
133
134// static
135rtc::PlatformThread TaskQueueStdlib::InitializeThread(
136 TaskQueueStdlib* me,
137 absl::string_view queue_name,
138 rtc::ThreadPriority priority) {
139 rtc::Event started;
140 auto thread = rtc::PlatformThread::SpawnJoinable(
141 [&started, me] {
142 CurrentTaskQueueSetter set_current(me);
143 started.Set();
144 me->ProcessTasks();
145 },
146 queue_name, rtc::ThreadAttributes().SetPriority(priority));
147 started.Wait(rtc::Event::kForever);
148 return thread;
Robin Raymond22027b92018-11-23 09:07:50 -0500149}
150
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100151void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500152 RTC_DCHECK(!IsCurrent());
153
154 {
Markus Handell18523c32020-07-08 17:55:58 +0200155 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500156 thread_should_quit_ = true;
157 }
158
159 NotifyWake();
160
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100161 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500162}
163
Danil Chapovalovba570012022-07-19 18:36:31 +0200164void TaskQueueStdlib::PostTask(absl::AnyInvocable<void() &&> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500165 {
Markus Handell18523c32020-07-08 17:55:58 +0200166 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200167 pending_queue_.push(
168 std::make_pair(++thread_posting_order_, std::move(task)));
Robin Raymond22027b92018-11-23 09:07:50 -0500169 }
170
171 NotifyWake();
172}
173
Danil Chapovalovba570012022-07-19 18:36:31 +0200174void TaskQueueStdlib::PostDelayedTask(absl::AnyInvocable<void() &&> task,
175 TimeDelta delay) {
176 DelayedEntryTimeout delayed_entry;
177 delayed_entry.next_fire_at_us = rtc::TimeMicros() + delay.us();
Robin Raymond22027b92018-11-23 09:07:50 -0500178
179 {
Markus Handell18523c32020-07-08 17:55:58 +0200180 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200181 delayed_entry.order = ++thread_posting_order_;
182 delayed_queue_[delayed_entry] = std::move(task);
Robin Raymond22027b92018-11-23 09:07:50 -0500183 }
184
185 NotifyWake();
186}
187
Danil Chapovalovba570012022-07-19 18:36:31 +0200188void TaskQueueStdlib::PostDelayedHighPrecisionTask(
189 absl::AnyInvocable<void() &&> task,
190 TimeDelta delay) {
191 PostDelayedTask(std::move(task), delay);
192}
193
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100194TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Tommi76d9c182022-04-22 15:48:37 +0200195 NextTask result;
Robin Raymond22027b92018-11-23 09:07:50 -0500196
Danil Chapovalovba570012022-07-19 18:36:31 +0200197 const int64_t tick_us = rtc::TimeMicros();
Robin Raymond22027b92018-11-23 09:07:50 -0500198
Markus Handell18523c32020-07-08 17:55:58 +0200199 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500200
201 if (thread_should_quit_) {
Danil Chapovalovba570012022-07-19 18:36:31 +0200202 result.final_task = true;
Robin Raymond22027b92018-11-23 09:07:50 -0500203 return result;
204 }
205
206 if (delayed_queue_.size() > 0) {
207 auto delayed_entry = delayed_queue_.begin();
208 const auto& delay_info = delayed_entry->first;
209 auto& delay_run = delayed_entry->second;
Danil Chapovalovba570012022-07-19 18:36:31 +0200210 if (tick_us >= delay_info.next_fire_at_us) {
Robin Raymond22027b92018-11-23 09:07:50 -0500211 if (pending_queue_.size() > 0) {
212 auto& entry = pending_queue_.front();
213 auto& entry_order = entry.first;
214 auto& entry_run = entry.second;
Danil Chapovalovba570012022-07-19 18:36:31 +0200215 if (entry_order < delay_info.order) {
216 result.run_task = std::move(entry_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500217 pending_queue_.pop();
218 return result;
219 }
220 }
221
Danil Chapovalovba570012022-07-19 18:36:31 +0200222 result.run_task = std::move(delay_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500223 delayed_queue_.erase(delayed_entry);
224 return result;
225 }
226
Danil Chapovalovba570012022-07-19 18:36:31 +0200227 result.sleep_time_ms =
228 DivideRoundUp(delay_info.next_fire_at_us - tick_us, 1'000);
Robin Raymond22027b92018-11-23 09:07:50 -0500229 }
230
231 if (pending_queue_.size() > 0) {
232 auto& entry = pending_queue_.front();
Danil Chapovalovba570012022-07-19 18:36:31 +0200233 result.run_task = std::move(entry.second);
Robin Raymond22027b92018-11-23 09:07:50 -0500234 pending_queue_.pop();
235 }
236
237 return result;
238}
239
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100240void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500241 while (true) {
242 auto task = GetNextTask();
243
Danil Chapovalovba570012022-07-19 18:36:31 +0200244 if (task.final_task)
Robin Raymond22027b92018-11-23 09:07:50 -0500245 break;
246
Danil Chapovalovba570012022-07-19 18:36:31 +0200247 if (task.run_task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500248 // process entry immediately then try again
Danil Chapovalovba570012022-07-19 18:36:31 +0200249 std::move(task.run_task)();
Robin Raymond22027b92018-11-23 09:07:50 -0500250
Tommi76d9c182022-04-22 15:48:37 +0200251 // Attempt to run more tasks before going to sleep.
Robin Raymond22027b92018-11-23 09:07:50 -0500252 continue;
253 }
254
Markus Handell6df49b92022-08-17 13:39:59 +0000255 // TODO(bugs.webrtc.org/14366): While transitioning to TimeDelta, WebRTC and
256 // Chromium has a different idea about what type rtc::Event::kForever is.
257 // Code can't assume rtc::Event::kForever is the same type as timed wait
258 // arguments.
259 // Simplify after transitioning is complete.
260 if (task.sleep_time_ms.has_value())
261 flag_notify_.Wait(task.sleep_time_ms.value());
262 else
263 flag_notify_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 09:07:50 -0500264 }
Robin Raymond22027b92018-11-23 09:07:50 -0500265}
266
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100267void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 09:07:50 -0500268 // The queue holds pending tasks to complete. Either tasks are to be
269 // executed immediately or tasks are to be run at some future delayed time.
270 // For immediate tasks the task queue's thread is busy running the task and
271 // the thread will not be waiting on the flag_notify_ event. If no immediate
272 // tasks are available but a delayed task is pending then the thread will be
273 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
274 // to run. If no immediate or pending tasks are available, the thread will
275 // wait on flag_notify_ until signaled that a task has been added (or the
276 // thread to be told to shutdown).
277
278 // In all cases, when a new immediate task, delayed task, or request to
279 // shutdown the thread is added the flag_notify_ is signaled after. If the
280 // thread was waiting then the thread will wake up immediately and re-assess
281 // what task needs to be run next (i.e. run a task now, wait for the nearest
282 // timed delayed task, or shutdown the thread). If the thread was not waiting
283 // then the thread will remained signaled to wake up the next time any
284 // attempt to wait on the flag_notify_ event occurs.
285
286 // Any immediate or delayed pending task (or request to shutdown the thread)
287 // must always be added to the queue prior to signaling flag_notify_ to wake
288 // up the possibly sleeping thread. This prevents a race condition where the
289 // thread is notified to wake up but the task queue's thread finds nothing to
290 // do so it waits once again to be signaled where such a signal may never
291 // happen.
292 flag_notify_.Set();
293}
294
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100295class TaskQueueStdlibFactory final : public TaskQueueFactory {
296 public:
297 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
298 absl::string_view name,
299 Priority priority) const override {
300 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
301 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
302 }
303};
304
305} // namespace
306
307std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200308 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 09:07:50 -0500309}
310
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100311} // namespace webrtc