blob: 19e7dead976800ca6d5a05220948e5854f7119df [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;
77 int64_t sleep_time_ms = rtc::Event::kForever;
Robin Raymond22027b92018-11-23 09:07:50 -050078 };
79
Tommi76d9c182022-04-22 15:48:37 +020080 static rtc::PlatformThread InitializeThread(TaskQueueStdlib* me,
81 absl::string_view queue_name,
82 rtc::ThreadPriority priority);
83
Robin Raymond22027b92018-11-23 09:07:50 -050084 NextTask GetNextTask();
85
Robin Raymond22027b92018-11-23 09:07:50 -050086 void ProcessTasks();
87
88 void NotifyWake();
89
Robin Raymond22027b92018-11-23 09:07:50 -050090 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010091 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050092
Markus Handell18523c32020-07-08 17:55:58 +020093 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -050094
95 // Indicates if the worker thread needs to shutdown now.
Tommi76d9c182022-04-22 15:48:37 +020096 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_) = false;
Robin Raymond22027b92018-11-23 09:07:50 -050097
98 // Holds the next order to use for the next task to be
99 // put into one of the pending queues.
Tommi76d9c182022-04-22 15:48:37 +0200100 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_) = 0;
Robin Raymond22027b92018-11-23 09:07:50 -0500101
102 // The list of all pending tasks that need to be processed in the
103 // FIFO queue ordering on the worker thread.
Danil Chapovalovba570012022-07-19 18:36:31 +0200104 std::queue<std::pair<OrderId, absl::AnyInvocable<void() &&>>> pending_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500105 RTC_GUARDED_BY(pending_lock_);
106
107 // The list of all pending tasks that need to be processed at a future
108 // time based upon a delay. On the off change the delayed task should
109 // happen at exactly the same time interval as another task then the
110 // task is processed based on FIFO ordering. std::priority_queue was
111 // considered but rejected due to its inability to extract the
Danil Chapovalovba570012022-07-19 18:36:31 +0200112 // move-only value out of the queue without the presence of a hack.
113 std::map<DelayedEntryTimeout, absl::AnyInvocable<void() &&>> delayed_queue_
Robin Raymond22027b92018-11-23 09:07:50 -0500114 RTC_GUARDED_BY(pending_lock_);
Markus Handell49cb4592021-06-22 10:02:26 +0200115
116 // Contains the active worker thread assigned to processing
117 // tasks (including delayed tasks).
118 // Placing this last ensures the thread doesn't touch uninitialized attributes
119 // throughout it's lifetime.
120 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 09:07:50 -0500121};
122
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100123TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
124 rtc::ThreadPriority priority)
Tommi76d9c182022-04-22 15:48:37 +0200125 : flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
126 thread_(InitializeThread(this, queue_name, priority)) {}
127
128// static
129rtc::PlatformThread TaskQueueStdlib::InitializeThread(
130 TaskQueueStdlib* me,
131 absl::string_view queue_name,
132 rtc::ThreadPriority priority) {
133 rtc::Event started;
134 auto thread = rtc::PlatformThread::SpawnJoinable(
135 [&started, me] {
136 CurrentTaskQueueSetter set_current(me);
137 started.Set();
138 me->ProcessTasks();
139 },
140 queue_name, rtc::ThreadAttributes().SetPriority(priority));
141 started.Wait(rtc::Event::kForever);
142 return thread;
Robin Raymond22027b92018-11-23 09:07:50 -0500143}
144
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100145void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500146 RTC_DCHECK(!IsCurrent());
147
148 {
Markus Handell18523c32020-07-08 17:55:58 +0200149 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500150 thread_should_quit_ = true;
151 }
152
153 NotifyWake();
154
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100155 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500156}
157
Danil Chapovalovba570012022-07-19 18:36:31 +0200158void TaskQueueStdlib::PostTask(absl::AnyInvocable<void() &&> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500159 {
Markus Handell18523c32020-07-08 17:55:58 +0200160 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200161 pending_queue_.push(
162 std::make_pair(++thread_posting_order_, std::move(task)));
Robin Raymond22027b92018-11-23 09:07:50 -0500163 }
164
165 NotifyWake();
166}
167
Danil Chapovalovba570012022-07-19 18:36:31 +0200168void TaskQueueStdlib::PostDelayedTask(absl::AnyInvocable<void() &&> task,
169 TimeDelta delay) {
170 DelayedEntryTimeout delayed_entry;
171 delayed_entry.next_fire_at_us = rtc::TimeMicros() + delay.us();
Robin Raymond22027b92018-11-23 09:07:50 -0500172
173 {
Markus Handell18523c32020-07-08 17:55:58 +0200174 MutexLock lock(&pending_lock_);
Danil Chapovalovba570012022-07-19 18:36:31 +0200175 delayed_entry.order = ++thread_posting_order_;
176 delayed_queue_[delayed_entry] = std::move(task);
Robin Raymond22027b92018-11-23 09:07:50 -0500177 }
178
179 NotifyWake();
180}
181
Danil Chapovalovba570012022-07-19 18:36:31 +0200182void TaskQueueStdlib::PostDelayedHighPrecisionTask(
183 absl::AnyInvocable<void() &&> task,
184 TimeDelta delay) {
185 PostDelayedTask(std::move(task), delay);
186}
187
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100188TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Tommi76d9c182022-04-22 15:48:37 +0200189 NextTask result;
Robin Raymond22027b92018-11-23 09:07:50 -0500190
Danil Chapovalovba570012022-07-19 18:36:31 +0200191 const int64_t tick_us = rtc::TimeMicros();
Robin Raymond22027b92018-11-23 09:07:50 -0500192
Markus Handell18523c32020-07-08 17:55:58 +0200193 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500194
195 if (thread_should_quit_) {
Danil Chapovalovba570012022-07-19 18:36:31 +0200196 result.final_task = true;
Robin Raymond22027b92018-11-23 09:07:50 -0500197 return result;
198 }
199
200 if (delayed_queue_.size() > 0) {
201 auto delayed_entry = delayed_queue_.begin();
202 const auto& delay_info = delayed_entry->first;
203 auto& delay_run = delayed_entry->second;
Danil Chapovalovba570012022-07-19 18:36:31 +0200204 if (tick_us >= delay_info.next_fire_at_us) {
Robin Raymond22027b92018-11-23 09:07:50 -0500205 if (pending_queue_.size() > 0) {
206 auto& entry = pending_queue_.front();
207 auto& entry_order = entry.first;
208 auto& entry_run = entry.second;
Danil Chapovalovba570012022-07-19 18:36:31 +0200209 if (entry_order < delay_info.order) {
210 result.run_task = std::move(entry_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500211 pending_queue_.pop();
212 return result;
213 }
214 }
215
Danil Chapovalovba570012022-07-19 18:36:31 +0200216 result.run_task = std::move(delay_run);
Robin Raymond22027b92018-11-23 09:07:50 -0500217 delayed_queue_.erase(delayed_entry);
218 return result;
219 }
220
Danil Chapovalovba570012022-07-19 18:36:31 +0200221 result.sleep_time_ms =
222 DivideRoundUp(delay_info.next_fire_at_us - tick_us, 1'000);
Robin Raymond22027b92018-11-23 09:07:50 -0500223 }
224
225 if (pending_queue_.size() > 0) {
226 auto& entry = pending_queue_.front();
Danil Chapovalovba570012022-07-19 18:36:31 +0200227 result.run_task = std::move(entry.second);
Robin Raymond22027b92018-11-23 09:07:50 -0500228 pending_queue_.pop();
229 }
230
231 return result;
232}
233
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100234void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500235 while (true) {
236 auto task = GetNextTask();
237
Danil Chapovalovba570012022-07-19 18:36:31 +0200238 if (task.final_task)
Robin Raymond22027b92018-11-23 09:07:50 -0500239 break;
240
Danil Chapovalovba570012022-07-19 18:36:31 +0200241 if (task.run_task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500242 // process entry immediately then try again
Danil Chapovalovba570012022-07-19 18:36:31 +0200243 std::move(task.run_task)();
Robin Raymond22027b92018-11-23 09:07:50 -0500244
Tommi76d9c182022-04-22 15:48:37 +0200245 // Attempt to run more tasks before going to sleep.
Robin Raymond22027b92018-11-23 09:07:50 -0500246 continue;
247 }
248
Danil Chapovalovba570012022-07-19 18:36:31 +0200249 flag_notify_.Wait(task.sleep_time_ms);
Robin Raymond22027b92018-11-23 09:07:50 -0500250 }
Robin Raymond22027b92018-11-23 09:07:50 -0500251}
252
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100253void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 09:07:50 -0500254 // The queue holds pending tasks to complete. Either tasks are to be
255 // executed immediately or tasks are to be run at some future delayed time.
256 // For immediate tasks the task queue's thread is busy running the task and
257 // the thread will not be waiting on the flag_notify_ event. If no immediate
258 // tasks are available but a delayed task is pending then the thread will be
259 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
260 // to run. If no immediate or pending tasks are available, the thread will
261 // wait on flag_notify_ until signaled that a task has been added (or the
262 // thread to be told to shutdown).
263
264 // In all cases, when a new immediate task, delayed task, or request to
265 // shutdown the thread is added the flag_notify_ is signaled after. If the
266 // thread was waiting then the thread will wake up immediately and re-assess
267 // what task needs to be run next (i.e. run a task now, wait for the nearest
268 // timed delayed task, or shutdown the thread). If the thread was not waiting
269 // then the thread will remained signaled to wake up the next time any
270 // attempt to wait on the flag_notify_ event occurs.
271
272 // Any immediate or delayed pending task (or request to shutdown the thread)
273 // must always be added to the queue prior to signaling flag_notify_ to wake
274 // up the possibly sleeping thread. This prevents a race condition where the
275 // thread is notified to wake up but the task queue's thread finds nothing to
276 // do so it waits once again to be signaled where such a signal may never
277 // happen.
278 flag_notify_.Set();
279}
280
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100281class TaskQueueStdlibFactory final : public TaskQueueFactory {
282 public:
283 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
284 absl::string_view name,
285 Priority priority) const override {
286 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
287 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
288 }
289};
290
291} // namespace
292
293std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200294 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 09:07:50 -0500295}
296
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100297} // namespace webrtc