blob: 946261ed58a87454d169651f77f90c6e4ea6188e [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 Chapovalovfa52efa2019-02-21 11:13:58 +010021#include "absl/strings/string_view.h"
22#include "api/task_queue/queued_task.h"
23#include "api/task_queue/task_queue_base.h"
Robin Raymond22027b92018-11-23 09:07:50 -050024#include "rtc_base/checks.h"
Robin Raymond22027b92018-11-23 09:07:50 -050025#include "rtc_base/event.h"
26#include "rtc_base/logging.h"
27#include "rtc_base/platform_thread.h"
Markus Handell18523c32020-07-08 17:55:58 +020028#include "rtc_base/synchronization/mutex.h"
Robin Raymond22027b92018-11-23 09:07:50 -050029#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 09:11:00 -080030#include "rtc_base/time_utils.h"
Robin Raymond22027b92018-11-23 09:07:50 -050031
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010032namespace webrtc {
Robin Raymond22027b92018-11-23 09:07:50 -050033namespace {
34
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010035rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
36 TaskQueueFactory::Priority priority) {
Robin Raymond22027b92018-11-23 09:07:50 -050037 switch (priority) {
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010038 case TaskQueueFactory::Priority::HIGH:
Markus Handellad5037b2021-05-07 15:02:36 +020039 return rtc::ThreadPriority::kRealtime;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010040 case TaskQueueFactory::Priority::LOW:
Markus Handellad5037b2021-05-07 15:02:36 +020041 return rtc::ThreadPriority::kLow;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010042 case TaskQueueFactory::Priority::NORMAL:
Markus Handellad5037b2021-05-07 15:02:36 +020043 return rtc::ThreadPriority::kNormal;
Robin Raymond22027b92018-11-23 09:07:50 -050044 }
Robin Raymond22027b92018-11-23 09:07:50 -050045}
46
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010047class TaskQueueStdlib final : public TaskQueueBase {
Robin Raymond22027b92018-11-23 09:07:50 -050048 public:
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010049 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
50 ~TaskQueueStdlib() override = default;
Robin Raymond22027b92018-11-23 09:07:50 -050051
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010052 void Delete() override;
53 void PostTask(std::unique_ptr<QueuedTask> task) override;
54 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
55 uint32_t milliseconds) override;
Robin Raymond22027b92018-11-23 09:07:50 -050056
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010057 private:
Robin Raymond22027b92018-11-23 09:07:50 -050058 using OrderId = uint64_t;
59
60 struct DelayedEntryTimeout {
61 int64_t next_fire_at_ms_{};
62 OrderId order_{};
63
64 bool operator<(const DelayedEntryTimeout& o) const {
65 return std::tie(next_fire_at_ms_, order_) <
66 std::tie(o.next_fire_at_ms_, o.order_);
67 }
68 };
69
70 struct NextTask {
Tommi76d9c182022-04-22 15:48:37 +020071 bool final_task_ = false;
Robin Raymond22027b92018-11-23 09:07:50 -050072 std::unique_ptr<QueuedTask> run_task_;
Tommi76d9c182022-04-22 15:48:37 +020073 int64_t sleep_time_ms_ = 0;
Robin Raymond22027b92018-11-23 09:07:50 -050074 };
75
Tommi76d9c182022-04-22 15:48:37 +020076 static rtc::PlatformThread InitializeThread(TaskQueueStdlib* me,
77 absl::string_view queue_name,
78 rtc::ThreadPriority priority);
79
Robin Raymond22027b92018-11-23 09:07:50 -050080 NextTask GetNextTask();
81
Robin Raymond22027b92018-11-23 09:07:50 -050082 void ProcessTasks();
83
84 void NotifyWake();
85
Robin Raymond22027b92018-11-23 09:07:50 -050086 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010087 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050088
Markus Handell18523c32020-07-08 17:55:58 +020089 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -050090
91 // Indicates if the worker thread needs to shutdown now.
Tommi76d9c182022-04-22 15:48:37 +020092 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_) = false;
Robin Raymond22027b92018-11-23 09:07:50 -050093
94 // Holds the next order to use for the next task to be
95 // put into one of the pending queues.
Tommi76d9c182022-04-22 15:48:37 +020096 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_) = 0;
Robin Raymond22027b92018-11-23 09:07:50 -050097
98 // The list of all pending tasks that need to be processed in the
99 // FIFO queue ordering on the worker thread.
100 std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
101 RTC_GUARDED_BY(pending_lock_);
102
103 // The list of all pending tasks that need to be processed at a future
104 // time based upon a delay. On the off change the delayed task should
105 // happen at exactly the same time interval as another task then the
106 // task is processed based on FIFO ordering. std::priority_queue was
107 // considered but rejected due to its inability to extract the
108 // std::unique_ptr out of the queue without the presence of a hack.
109 std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
110 RTC_GUARDED_BY(pending_lock_);
Markus Handell49cb4592021-06-22 10:02:26 +0200111
112 // Contains the active worker thread assigned to processing
113 // tasks (including delayed tasks).
114 // Placing this last ensures the thread doesn't touch uninitialized attributes
115 // throughout it's lifetime.
116 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 09:07:50 -0500117};
118
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100119TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
120 rtc::ThreadPriority priority)
Tommi76d9c182022-04-22 15:48:37 +0200121 : flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
122 thread_(InitializeThread(this, queue_name, priority)) {}
123
124// static
125rtc::PlatformThread TaskQueueStdlib::InitializeThread(
126 TaskQueueStdlib* me,
127 absl::string_view queue_name,
128 rtc::ThreadPriority priority) {
129 rtc::Event started;
130 auto thread = rtc::PlatformThread::SpawnJoinable(
131 [&started, me] {
132 CurrentTaskQueueSetter set_current(me);
133 started.Set();
134 me->ProcessTasks();
135 },
136 queue_name, rtc::ThreadAttributes().SetPriority(priority));
137 started.Wait(rtc::Event::kForever);
138 return thread;
Robin Raymond22027b92018-11-23 09:07:50 -0500139}
140
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100141void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500142 RTC_DCHECK(!IsCurrent());
143
144 {
Markus Handell18523c32020-07-08 17:55:58 +0200145 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500146 thread_should_quit_ = true;
147 }
148
149 NotifyWake();
150
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100151 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500152}
153
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100154void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500155 {
Markus Handell18523c32020-07-08 17:55:58 +0200156 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500157 OrderId order = thread_posting_order_++;
158
159 pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
160 order, std::move(task)));
161 }
162
163 NotifyWake();
164}
165
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100166void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
Robin Raymond22027b92018-11-23 09:07:50 -0500167 uint32_t milliseconds) {
Tommi76d9c182022-04-22 15:48:37 +0200168 const auto fire_at = rtc::TimeMillis() + milliseconds;
Robin Raymond22027b92018-11-23 09:07:50 -0500169
170 DelayedEntryTimeout delay;
171 delay.next_fire_at_ms_ = fire_at;
172
173 {
Markus Handell18523c32020-07-08 17:55:58 +0200174 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500175 delay.order_ = ++thread_posting_order_;
176 delayed_queue_[delay] = std::move(task);
177 }
178
179 NotifyWake();
180}
181
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100182TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Tommi76d9c182022-04-22 15:48:37 +0200183 NextTask result;
Robin Raymond22027b92018-11-23 09:07:50 -0500184
Tommi76d9c182022-04-22 15:48:37 +0200185 const auto tick = rtc::TimeMillis();
Robin Raymond22027b92018-11-23 09:07:50 -0500186
Markus Handell18523c32020-07-08 17:55:58 +0200187 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500188
189 if (thread_should_quit_) {
190 result.final_task_ = true;
191 return result;
192 }
193
194 if (delayed_queue_.size() > 0) {
195 auto delayed_entry = delayed_queue_.begin();
196 const auto& delay_info = delayed_entry->first;
197 auto& delay_run = delayed_entry->second;
198 if (tick >= delay_info.next_fire_at_ms_) {
199 if (pending_queue_.size() > 0) {
200 auto& entry = pending_queue_.front();
201 auto& entry_order = entry.first;
202 auto& entry_run = entry.second;
203 if (entry_order < delay_info.order_) {
204 result.run_task_ = std::move(entry_run);
205 pending_queue_.pop();
206 return result;
207 }
208 }
209
210 result.run_task_ = std::move(delay_run);
211 delayed_queue_.erase(delayed_entry);
212 return result;
213 }
214
215 result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
216 }
217
218 if (pending_queue_.size() > 0) {
219 auto& entry = pending_queue_.front();
220 result.run_task_ = std::move(entry.second);
221 pending_queue_.pop();
222 }
223
224 return result;
225}
226
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100227void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500228 while (true) {
229 auto task = GetNextTask();
230
231 if (task.final_task_)
232 break;
233
234 if (task.run_task_) {
235 // process entry immediately then try again
236 QueuedTask* release_ptr = task.run_task_.release();
237 if (release_ptr->Run())
238 delete release_ptr;
239
Tommi76d9c182022-04-22 15:48:37 +0200240 // Attempt to run more tasks before going to sleep.
Robin Raymond22027b92018-11-23 09:07:50 -0500241 continue;
242 }
243
Tommi76d9c182022-04-22 15:48:37 +0200244 flag_notify_.Wait(0 == task.sleep_time_ms_ ? rtc::Event::kForever
245 : task.sleep_time_ms_);
Robin Raymond22027b92018-11-23 09:07:50 -0500246 }
Robin Raymond22027b92018-11-23 09:07:50 -0500247}
248
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100249void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 09:07:50 -0500250 // The queue holds pending tasks to complete. Either tasks are to be
251 // executed immediately or tasks are to be run at some future delayed time.
252 // For immediate tasks the task queue's thread is busy running the task and
253 // the thread will not be waiting on the flag_notify_ event. If no immediate
254 // tasks are available but a delayed task is pending then the thread will be
255 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
256 // to run. If no immediate or pending tasks are available, the thread will
257 // wait on flag_notify_ until signaled that a task has been added (or the
258 // thread to be told to shutdown).
259
260 // In all cases, when a new immediate task, delayed task, or request to
261 // shutdown the thread is added the flag_notify_ is signaled after. If the
262 // thread was waiting then the thread will wake up immediately and re-assess
263 // what task needs to be run next (i.e. run a task now, wait for the nearest
264 // timed delayed task, or shutdown the thread). If the thread was not waiting
265 // then the thread will remained signaled to wake up the next time any
266 // attempt to wait on the flag_notify_ event occurs.
267
268 // Any immediate or delayed pending task (or request to shutdown the thread)
269 // must always be added to the queue prior to signaling flag_notify_ to wake
270 // up the possibly sleeping thread. This prevents a race condition where the
271 // thread is notified to wake up but the task queue's thread finds nothing to
272 // do so it waits once again to be signaled where such a signal may never
273 // happen.
274 flag_notify_.Set();
275}
276
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100277class TaskQueueStdlibFactory final : public TaskQueueFactory {
278 public:
279 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
280 absl::string_view name,
281 Priority priority) const override {
282 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
283 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
284 }
285};
286
287} // namespace
288
289std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200290 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 09:07:50 -0500291}
292
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100293} // namespace webrtc