blob: bd5bb9798834e70bc9b2979bacb358c0e4f7ee7d [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:
Guido Urdaneta793bac52021-05-06 13:12:47 +000039 return rtc::kRealtimePriority;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010040 case TaskQueueFactory::Priority::LOW:
Guido Urdaneta793bac52021-05-06 13:12:47 +000041 return rtc::kLowPriority;
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010042 case TaskQueueFactory::Priority::NORMAL:
Guido Urdaneta793bac52021-05-06 13:12:47 +000043 return rtc::kNormalPriority;
44 default:
45 RTC_NOTREACHED();
46 return rtc::kNormalPriority;
Robin Raymond22027b92018-11-23 09:07:50 -050047 }
Robin Raymond22027b92018-11-23 09:07:50 -050048}
49
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010050class TaskQueueStdlib final : public TaskQueueBase {
Robin Raymond22027b92018-11-23 09:07:50 -050051 public:
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010052 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
53 ~TaskQueueStdlib() override = default;
Robin Raymond22027b92018-11-23 09:07:50 -050054
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010055 void Delete() override;
56 void PostTask(std::unique_ptr<QueuedTask> task) override;
57 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
58 uint32_t milliseconds) override;
Robin Raymond22027b92018-11-23 09:07:50 -050059
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010060 private:
Robin Raymond22027b92018-11-23 09:07:50 -050061 using OrderId = uint64_t;
62
63 struct DelayedEntryTimeout {
64 int64_t next_fire_at_ms_{};
65 OrderId order_{};
66
67 bool operator<(const DelayedEntryTimeout& o) const {
68 return std::tie(next_fire_at_ms_, order_) <
69 std::tie(o.next_fire_at_ms_, o.order_);
70 }
71 };
72
73 struct NextTask {
74 bool final_task_{false};
75 std::unique_ptr<QueuedTask> run_task_;
76 int64_t sleep_time_ms_{};
77 };
78
Robin Raymond22027b92018-11-23 09:07:50 -050079 NextTask GetNextTask();
80
Guido Urdaneta793bac52021-05-06 13:12:47 +000081 static void ThreadMain(void* context);
82
Robin Raymond22027b92018-11-23 09:07:50 -050083 void ProcessTasks();
84
85 void NotifyWake();
86
Robin Raymond22027b92018-11-23 09:07:50 -050087 // Indicates if the thread has started.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010088 rtc::Event started_;
Robin Raymond22027b92018-11-23 09:07:50 -050089
90 // Indicates if the thread has stopped.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010091 rtc::Event stopped_;
Robin Raymond22027b92018-11-23 09:07:50 -050092
93 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010094 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 09:07:50 -050095
96 // Contains the active worker thread assigned to processing
97 // tasks (including delayed tasks).
Danil Chapovalovfa52efa2019-02-21 11:13:58 +010098 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 09:07:50 -050099
Markus Handell18523c32020-07-08 17:55:58 +0200100 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 09:07:50 -0500101
102 // Indicates if the worker thread needs to shutdown now.
103 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_){false};
104
105 // Holds the next order to use for the next task to be
106 // put into one of the pending queues.
107 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_){};
108
109 // The list of all pending tasks that need to be processed in the
110 // FIFO queue ordering on the worker thread.
111 std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
112 RTC_GUARDED_BY(pending_lock_);
113
114 // The list of all pending tasks that need to be processed at a future
115 // time based upon a delay. On the off change the delayed task should
116 // happen at exactly the same time interval as another task then the
117 // task is processed based on FIFO ordering. std::priority_queue was
118 // considered but rejected due to its inability to extract the
119 // std::unique_ptr out of the queue without the presence of a hack.
120 std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
121 RTC_GUARDED_BY(pending_lock_);
122};
123
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100124TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
125 rtc::ThreadPriority priority)
126 : started_(/*manual_reset=*/false, /*initially_signaled=*/false),
Robin Raymond22027b92018-11-23 09:07:50 -0500127 stopped_(/*manual_reset=*/false, /*initially_signaled=*/false),
128 flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
Guido Urdaneta793bac52021-05-06 13:12:47 +0000129 thread_(&TaskQueueStdlib::ThreadMain,
130 this,
131 queue_name,
132 rtc::ThreadAttributes().SetPriority(priority)) {
133 thread_.Start();
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100134 started_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 09:07:50 -0500135}
136
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100137void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 09:07:50 -0500138 RTC_DCHECK(!IsCurrent());
139
140 {
Markus Handell18523c32020-07-08 17:55:58 +0200141 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500142 thread_should_quit_ = true;
143 }
144
145 NotifyWake();
146
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100147 stopped_.Wait(rtc::Event::kForever);
Guido Urdaneta793bac52021-05-06 13:12:47 +0000148 thread_.Stop();
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100149 delete this;
Robin Raymond22027b92018-11-23 09:07:50 -0500150}
151
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100152void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
Robin Raymond22027b92018-11-23 09:07:50 -0500153 {
Markus Handell18523c32020-07-08 17:55:58 +0200154 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500155 OrderId order = thread_posting_order_++;
156
157 pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
158 order, std::move(task)));
159 }
160
161 NotifyWake();
162}
163
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100164void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
Robin Raymond22027b92018-11-23 09:07:50 -0500165 uint32_t milliseconds) {
166 auto fire_at = rtc::TimeMillis() + milliseconds;
167
168 DelayedEntryTimeout delay;
169 delay.next_fire_at_ms_ = fire_at;
170
171 {
Markus Handell18523c32020-07-08 17:55:58 +0200172 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500173 delay.order_ = ++thread_posting_order_;
174 delayed_queue_[delay] = std::move(task);
175 }
176
177 NotifyWake();
178}
179
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100180TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Robin Raymond22027b92018-11-23 09:07:50 -0500181 NextTask result{};
182
183 auto tick = rtc::TimeMillis();
184
Markus Handell18523c32020-07-08 17:55:58 +0200185 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 09:07:50 -0500186
187 if (thread_should_quit_) {
188 result.final_task_ = true;
189 return result;
190 }
191
192 if (delayed_queue_.size() > 0) {
193 auto delayed_entry = delayed_queue_.begin();
194 const auto& delay_info = delayed_entry->first;
195 auto& delay_run = delayed_entry->second;
196 if (tick >= delay_info.next_fire_at_ms_) {
197 if (pending_queue_.size() > 0) {
198 auto& entry = pending_queue_.front();
199 auto& entry_order = entry.first;
200 auto& entry_run = entry.second;
201 if (entry_order < delay_info.order_) {
202 result.run_task_ = std::move(entry_run);
203 pending_queue_.pop();
204 return result;
205 }
206 }
207
208 result.run_task_ = std::move(delay_run);
209 delayed_queue_.erase(delayed_entry);
210 return result;
211 }
212
213 result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
214 }
215
216 if (pending_queue_.size() > 0) {
217 auto& entry = pending_queue_.front();
218 result.run_task_ = std::move(entry.second);
219 pending_queue_.pop();
220 }
221
222 return result;
223}
224
Guido Urdaneta793bac52021-05-06 13:12:47 +0000225// static
226void TaskQueueStdlib::ThreadMain(void* context) {
227 TaskQueueStdlib* me = static_cast<TaskQueueStdlib*>(context);
228 CurrentTaskQueueSetter set_current(me);
229 me->ProcessTasks();
230}
231
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100232void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 09:07:50 -0500233 started_.Set();
234
235 while (true) {
236 auto task = GetNextTask();
237
238 if (task.final_task_)
239 break;
240
241 if (task.run_task_) {
242 // process entry immediately then try again
243 QueuedTask* release_ptr = task.run_task_.release();
244 if (release_ptr->Run())
245 delete release_ptr;
246
247 // attempt to sleep again
248 continue;
249 }
250
251 if (0 == task.sleep_time_ms_)
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100252 flag_notify_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 09:07:50 -0500253 else
254 flag_notify_.Wait(task.sleep_time_ms_);
255 }
256
257 stopped_.Set();
258}
259
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100260void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 09:07:50 -0500261 // The queue holds pending tasks to complete. Either tasks are to be
262 // executed immediately or tasks are to be run at some future delayed time.
263 // For immediate tasks the task queue's thread is busy running the task and
264 // the thread will not be waiting on the flag_notify_ event. If no immediate
265 // tasks are available but a delayed task is pending then the thread will be
266 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
267 // to run. If no immediate or pending tasks are available, the thread will
268 // wait on flag_notify_ until signaled that a task has been added (or the
269 // thread to be told to shutdown).
270
271 // In all cases, when a new immediate task, delayed task, or request to
272 // shutdown the thread is added the flag_notify_ is signaled after. If the
273 // thread was waiting then the thread will wake up immediately and re-assess
274 // what task needs to be run next (i.e. run a task now, wait for the nearest
275 // timed delayed task, or shutdown the thread). If the thread was not waiting
276 // then the thread will remained signaled to wake up the next time any
277 // attempt to wait on the flag_notify_ event occurs.
278
279 // Any immediate or delayed pending task (or request to shutdown the thread)
280 // must always be added to the queue prior to signaling flag_notify_ to wake
281 // up the possibly sleeping thread. This prevents a race condition where the
282 // thread is notified to wake up but the task queue's thread finds nothing to
283 // do so it waits once again to be signaled where such a signal may never
284 // happen.
285 flag_notify_.Set();
286}
287
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100288class TaskQueueStdlibFactory final : public TaskQueueFactory {
289 public:
290 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
291 absl::string_view name,
292 Priority priority) const override {
293 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
294 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
295 }
296};
297
298} // namespace
299
300std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 17:06:18 +0200301 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 09:07:50 -0500302}
303
Danil Chapovalovfa52efa2019-02-21 11:13:58 +0100304} // namespace webrtc