blob: 300873ac15328adbb8aaf4cbbcf8e3f5ff722c4f [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 {
Markus Handell2cfc1af2022-08-19 08:16:48 +000065 // TODO(bugs.webrtc.org/13756): Migrate to Timestamp.
Danil Chapovalovba570012022-07-19 18:36:31 +020066 int64_t next_fire_at_us{};
67 OrderId order{};
Robin Raymond22027b92018-11-23 09:07:50 -050068
69 bool operator<(const DelayedEntryTimeout& o) const {
Danil Chapovalovba570012022-07-19 18:36:31 +020070 return std::tie(next_fire_at_us, order) <
71 std::tie(o.next_fire_at_us, o.order);
Robin Raymond22027b92018-11-23 09:07:50 -050072 }
73 };
74
75 struct NextTask {
Danil Chapovalovba570012022-07-19 18:36:31 +020076 bool final_task = false;
77 absl::AnyInvocable<void() &&> run_task;
Markus Handell2cfc1af2022-08-19 08:16:48 +000078 TimeDelta sleep_time = rtc::Event::kForever;
Robin Raymond22027b92018-11-23 09:07:50 -050079 };
80
Tommi76d9c182022-04-22 15:48:37 +020081 static rtc::PlatformThread InitializeThread(TaskQueueStdlib* me,
82 absl::string_view queue_name,
83 rtc::ThreadPriority priority);
84
Robin Raymond22027b92018-11-23 09:07:50 -050085 NextTask GetNextTask();
86
Robin Raymond22027b92018-11-23 09:07:50 -050087 void ProcessTasks();
88
89 void NotifyWake();
90
Robin Raymond22027b92018-11-23 09:07:50 -050091 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010092 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050093
Markus Handell18523c32020-07-08 17:55:58 +020094 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -050095
96 // Indicates if the worker thread needs to shutdown now.
Tommi76d9c182022-04-22 15:48:37 +020097 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_) = false;
Robin Raymond22027b92018-11-23 09:07:50 -050098
99 // Holds the next order to use for the next task to be
100 // put into one of the pending queues.
Tommi76d9c182022-04-22 15:48:37 +0200101 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_) = 0;
Robin Raymond22027b92018-11-23 09:07:50 -0500102
103 // The list of all pending tasks that need to be processed in the
104 // FIFO queue ordering on the worker thread.
Danil Chapovalovba570012022-07-19 18:36:31 +0200105 std::queue<std::pair<OrderId, absl::AnyInvocable<void() &&>>> pending_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500106 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
Danil Chapovalovba570012022-07-19 18:36:31 +0200113 // move-only value out of the queue without the presence of a hack.
114 std::map<DelayedEntryTimeout, absl::AnyInvocable<void() &&>> delayed_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500115 RTC_GUARDED_BY(pending_lock_);
Markus Handell49cb4592021-06-22 10:02:26 +0200116
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_;
Robin Raymond22027b92018-11-23 09:07:50 -0500122};
123
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100124TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
125 rtc::ThreadPriority priority)
Tommi76d9c182022-04-22 15:48:37 +0200126 : flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
127 thread_(InitializeThread(this, queue_name, priority)) {}
128
129// static
130rtc::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;
Robin Raymond22027b92018-11-23 09:07:50 -0500144}
145
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100146void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500147 RTC_DCHECK(!IsCurrent());
148
149 {
Markus Handell18523c32020-07-08 17:55:58 +0200150 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500151 thread_should_quit_ = true;
152 }
153
154 NotifyWake();
155
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100156 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500157}
158
Danil Chapovalovba570012022-07-19 18:36:31 +0200159void TaskQueueStdlib::PostTask(absl::AnyInvocable<void() &&> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500160 {
Markus Handell18523c32020-07-08 17:55:58 +0200161 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200162 pending_queue_.push(
163 std::make_pair(++thread_posting_order_, std::move(task)));
Robin Raymond22027b92018-11-23 09:07:50 -0500164 }
165
166 NotifyWake();
167}
168
Danil Chapovalovba570012022-07-19 18:36:31 +0200169void TaskQueueStdlib::PostDelayedTask(absl::AnyInvocable<void() &&> task,
170 TimeDelta delay) {
171 DelayedEntryTimeout delayed_entry;
172 delayed_entry.next_fire_at_us = rtc::TimeMicros() + delay.us();
Robin Raymond22027b92018-11-23 09:07:50 -0500173
174 {
Markus Handell18523c32020-07-08 17:55:58 +0200175 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200176 delayed_entry.order = ++thread_posting_order_;
177 delayed_queue_[delayed_entry] = std::move(task);
Robin Raymond22027b92018-11-23 09:07:50 -0500178 }
179
180 NotifyWake();
181}
182
Danil Chapovalovba570012022-07-19 18:36:31 +0200183void TaskQueueStdlib::PostDelayedHighPrecisionTask(
184 absl::AnyInvocable<void() &&> task,
185 TimeDelta delay) {
186 PostDelayedTask(std::move(task), delay);
187}
188
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100189TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Tommi76d9c182022-04-22 15:48:37 +0200190 NextTask result;
Robin Raymond22027b92018-11-23 09:07:50 -0500191
Danil Chapovalovba570012022-07-19 18:36:31 +0200192 const int64_t tick_us = rtc::TimeMicros();
Robin Raymond22027b92018-11-23 09:07:50 -0500193
Markus Handell18523c32020-07-08 17:55:58 +0200194 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500195
196 if (thread_should_quit_) {
Danil Chapovalovba570012022-07-19 18:36:31 +0200197 result.final_task = true;
Robin Raymond22027b92018-11-23 09:07:50 -0500198 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;
Danil Chapovalovba570012022-07-19 18:36:31 +0200205 if (tick_us >= delay_info.next_fire_at_us) {
Robin Raymond22027b92018-11-23 09:07:50 -0500206 if (pending_queue_.size() > 0) {
207 auto& entry = pending_queue_.front();
208 auto& entry_order = entry.first;
209 auto& entry_run = entry.second;
Danil Chapovalovba570012022-07-19 18:36:31 +0200210 if (entry_order < delay_info.order) {
211 result.run_task = std::move(entry_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500212 pending_queue_.pop();
213 return result;
214 }
215 }
216
Danil Chapovalovba570012022-07-19 18:36:31 +0200217 result.run_task = std::move(delay_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500218 delayed_queue_.erase(delayed_entry);
219 return result;
220 }
221
Markus Handell2cfc1af2022-08-19 08:16:48 +0000222 result.sleep_time = TimeDelta::Millis(
223 DivideRoundUp(delay_info.next_fire_at_us - tick_us, 1'000));
Robin Raymond22027b92018-11-23 09:07:50 -0500224 }
225
226 if (pending_queue_.size() > 0) {
227 auto& entry = pending_queue_.front();
Danil Chapovalovba570012022-07-19 18:36:31 +0200228 result.run_task = std::move(entry.second);
Robin Raymond22027b92018-11-23 09:07:50 -0500229 pending_queue_.pop();
230 }
231
232 return result;
233}
234
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100235void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500236 while (true) {
237 auto task = GetNextTask();
238
Danil Chapovalovba570012022-07-19 18:36:31 +0200239 if (task.final_task)
Robin Raymond22027b92018-11-23 09:07:50 -0500240 break;
241
Danil Chapovalovba570012022-07-19 18:36:31 +0200242 if (task.run_task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500243 // process entry immediately then try again
Danil Chapovalovba570012022-07-19 18:36:31 +0200244 std::move(task.run_task)();
Robin Raymond22027b92018-11-23 09:07:50 -0500245
Tommi76d9c182022-04-22 15:48:37 +0200246 // Attempt to run more tasks before going to sleep.
Robin Raymond22027b92018-11-23 09:07:50 -0500247 continue;
248 }
249
Markus Handell2cfc1af2022-08-19 08:16:48 +0000250 flag_notify_.Wait(task.sleep_time);
Robin Raymond22027b92018-11-23 09:07:50 -0500251 }
Markus Handell82da9322022-12-16 15:50:24 +0100252
253 // Ensure remaining deleted tasks are destroyed with Current() set up to this
254 // task queue.
255 std::queue<std::pair<OrderId, absl::AnyInvocable<void() &&>>> pending_queue;
256 {
257 MutexLock lock(&pending_lock_);
258 pending_queue_.swap(pending_queue);
259 }
260 pending_queue = {};
261#if RTC_DCHECK_IS_ON
262 MutexLock lock(&pending_lock_);
263 RTC_DCHECK(pending_queue_.empty());
264#endif
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