blob: 548f7ef69add72b5086c473efc9daa4b37e6a054 [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 {
71 bool final_task_{false};
72 std::unique_ptr<QueuedTask> run_task_;
73 int64_t sleep_time_ms_{};
74 };
75
Robin Raymond22027b92018-11-23 09:07:50 -050076 NextTask GetNextTask();
77
Robin Raymond22027b92018-11-23 09:07:50 -050078 void ProcessTasks();
79
80 void NotifyWake();
81
Robin Raymond22027b92018-11-23 09:07:50 -050082 // Indicates if the thread has started.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010083 rtc::Event started_;
Robin Raymond22027b92018-11-23 09:07:50 -050084
85 // Indicates if the thread has stopped.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010086 rtc::Event stopped_;
Robin Raymond22027b92018-11-23 09:07:50 -050087
88 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010089 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050090
91 // Contains the active worker thread assigned to processing
92 // tasks (including delayed tasks).
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010093 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 09:07:50 -050094
Markus Handell18523c32020-07-08 17:55:58 +020095 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -050096
97 // Indicates if the worker thread needs to shutdown now.
98 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_){false};
99
100 // Holds the next order to use for the next task to be
101 // put into one of the pending queues.
102 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_){};
103
104 // The list of all pending tasks that need to be processed in the
105 // FIFO queue ordering on the worker thread.
106 std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
107 RTC_GUARDED_BY(pending_lock_);
108
109 // The list of all pending tasks that need to be processed at a future
110 // time based upon a delay. On the off change the delayed task should
111 // happen at exactly the same time interval as another task then the
112 // task is processed based on FIFO ordering. std::priority_queue was
113 // considered but rejected due to its inability to extract the
114 // std::unique_ptr out of the queue without the presence of a hack.
115 std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
116 RTC_GUARDED_BY(pending_lock_);
117};
118
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100119TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
120 rtc::ThreadPriority priority)
121 : started_(/*manual_reset=*/false, /*initially_signaled=*/false),
Robin Raymond22027b92018-11-23 09:07:50 -0500122 stopped_(/*manual_reset=*/false, /*initially_signaled=*/false),
123 flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
Markus Handellad5037b2021-05-07 15:02:36 +0200124 thread_(rtc::PlatformThread::SpawnJoinable(
125 [this] {
126 CurrentTaskQueueSetter set_current(this);
127 ProcessTasks();
128 },
129 queue_name,
130 rtc::ThreadAttributes().SetPriority(priority))) {
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100131 started_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 09:07:50 -0500132}
133
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100134void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500135 RTC_DCHECK(!IsCurrent());
136
137 {
Markus Handell18523c32020-07-08 17:55:58 +0200138 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500139 thread_should_quit_ = true;
140 }
141
142 NotifyWake();
143
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100144 stopped_.Wait(rtc::Event::kForever);
Markus Handellad5037b2021-05-07 15:02:36 +0200145 thread_.Finalize();
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100146 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500147}
148
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100149void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500150 {
Markus Handell18523c32020-07-08 17:55:58 +0200151 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500152 OrderId order = thread_posting_order_++;
153
154 pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
155 order, std::move(task)));
156 }
157
158 NotifyWake();
159}
160
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100161void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
Robin Raymond22027b92018-11-23 09:07:50 -0500162 uint32_t milliseconds) {
163 auto fire_at = rtc::TimeMillis() + milliseconds;
164
165 DelayedEntryTimeout delay;
166 delay.next_fire_at_ms_ = fire_at;
167
168 {
Markus Handell18523c32020-07-08 17:55:58 +0200169 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500170 delay.order_ = ++thread_posting_order_;
171 delayed_queue_[delay] = std::move(task);
172 }
173
174 NotifyWake();
175}
176
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100177TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Robin Raymond22027b92018-11-23 09:07:50 -0500178 NextTask result{};
179
180 auto tick = rtc::TimeMillis();
181
Markus Handell18523c32020-07-08 17:55:58 +0200182 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500183
184 if (thread_should_quit_) {
185 result.final_task_ = true;
186 return result;
187 }
188
189 if (delayed_queue_.size() > 0) {
190 auto delayed_entry = delayed_queue_.begin();
191 const auto& delay_info = delayed_entry->first;
192 auto& delay_run = delayed_entry->second;
193 if (tick >= delay_info.next_fire_at_ms_) {
194 if (pending_queue_.size() > 0) {
195 auto& entry = pending_queue_.front();
196 auto& entry_order = entry.first;
197 auto& entry_run = entry.second;
198 if (entry_order < delay_info.order_) {
199 result.run_task_ = std::move(entry_run);
200 pending_queue_.pop();
201 return result;
202 }
203 }
204
205 result.run_task_ = std::move(delay_run);
206 delayed_queue_.erase(delayed_entry);
207 return result;
208 }
209
210 result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
211 }
212
213 if (pending_queue_.size() > 0) {
214 auto& entry = pending_queue_.front();
215 result.run_task_ = std::move(entry.second);
216 pending_queue_.pop();
217 }
218
219 return result;
220}
221
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100222void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500223 started_.Set();
224
225 while (true) {
226 auto task = GetNextTask();
227
228 if (task.final_task_)
229 break;
230
231 if (task.run_task_) {
232 // process entry immediately then try again
233 QueuedTask* release_ptr = task.run_task_.release();
234 if (release_ptr->Run())
235 delete release_ptr;
236
237 // attempt to sleep again
238 continue;
239 }
240
241 if (0 == task.sleep_time_ms_)
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100242 flag_notify_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 09:07:50 -0500243 else
244 flag_notify_.Wait(task.sleep_time_ms_);
245 }
246
247 stopped_.Set();
248}
249
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100250void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 09:07:50 -0500251 // The queue holds pending tasks to complete. Either tasks are to be
252 // executed immediately or tasks are to be run at some future delayed time.
253 // For immediate tasks the task queue's thread is busy running the task and
254 // the thread will not be waiting on the flag_notify_ event. If no immediate
255 // tasks are available but a delayed task is pending then the thread will be
256 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
257 // to run. If no immediate or pending tasks are available, the thread will
258 // wait on flag_notify_ until signaled that a task has been added (or the
259 // thread to be told to shutdown).
260
261 // In all cases, when a new immediate task, delayed task, or request to
262 // shutdown the thread is added the flag_notify_ is signaled after. If the
263 // thread was waiting then the thread will wake up immediately and re-assess
264 // what task needs to be run next (i.e. run a task now, wait for the nearest
265 // timed delayed task, or shutdown the thread). If the thread was not waiting
266 // then the thread will remained signaled to wake up the next time any
267 // attempt to wait on the flag_notify_ event occurs.
268
269 // Any immediate or delayed pending task (or request to shutdown the thread)
270 // must always be added to the queue prior to signaling flag_notify_ to wake
271 // up the possibly sleeping thread. This prevents a race condition where the
272 // thread is notified to wake up but the task queue's thread finds nothing to
273 // do so it waits once again to be signaled where such a signal may never
274 // happen.
275 flag_notify_.Set();
276}
277
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100278class TaskQueueStdlibFactory final : public TaskQueueFactory {
279 public:
280 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
281 absl::string_view name,
282 Priority priority) const override {
283 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
284 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
285 }
286};
287
288} // namespace
289
290std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200291 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 09:07:50 -0500292}
293
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100294} // namespace webrtc