blob: 41da285ee74b84ff88946598d215d5b020ea51bc [file] [log] [blame]
Robin Raymond22027b92018-11-23 14:07:501/*
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 10:13:5811#include "rtc_base/task_queue_stdlib.h"
Robin Raymond22027b92018-11-23 14:07:5012
13#include <string.h>
Jonas Olssona4d87372019-07-05 17:08:3314
Robin Raymond22027b92018-11-23 14:07:5015#include <algorithm>
Robin Raymond22027b92018-11-23 14:07:5016#include <map>
Mirko Bonadei317a1f02019-09-17 15:06:1817#include <memory>
Robin Raymond22027b92018-11-23 14:07:5018#include <queue>
19#include <utility>
20
Danil Chapovalovfa52efa2019-02-21 10:13:5821#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 14:07:5024#include "rtc_base/checks.h"
Robin Raymond22027b92018-11-23 14:07:5025#include "rtc_base/event.h"
26#include "rtc_base/logging.h"
27#include "rtc_base/platform_thread.h"
Markus Handell18523c32020-07-08 15:55:5828#include "rtc_base/synchronization/mutex.h"
Robin Raymond22027b92018-11-23 14:07:5029#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 17:11:0030#include "rtc_base/time_utils.h"
Robin Raymond22027b92018-11-23 14:07:5031
Danil Chapovalovfa52efa2019-02-21 10:13:5832namespace webrtc {
Robin Raymond22027b92018-11-23 14:07:5033namespace {
34
Danil Chapovalovfa52efa2019-02-21 10:13:5835rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
36 TaskQueueFactory::Priority priority) {
Robin Raymond22027b92018-11-23 14:07:5037 switch (priority) {
Danil Chapovalovfa52efa2019-02-21 10:13:5838 case TaskQueueFactory::Priority::HIGH:
Markus Handellad5037b2021-05-07 13:02:3639 return rtc::ThreadPriority::kRealtime;
Danil Chapovalovfa52efa2019-02-21 10:13:5840 case TaskQueueFactory::Priority::LOW:
Markus Handellad5037b2021-05-07 13:02:3641 return rtc::ThreadPriority::kLow;
Danil Chapovalovfa52efa2019-02-21 10:13:5842 case TaskQueueFactory::Priority::NORMAL:
Markus Handellad5037b2021-05-07 13:02:3643 return rtc::ThreadPriority::kNormal;
Robin Raymond22027b92018-11-23 14:07:5044 }
Robin Raymond22027b92018-11-23 14:07:5045}
46
Danil Chapovalovfa52efa2019-02-21 10:13:5847class TaskQueueStdlib final : public TaskQueueBase {
Robin Raymond22027b92018-11-23 14:07:5048 public:
Danil Chapovalovfa52efa2019-02-21 10:13:5849 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
50 ~TaskQueueStdlib() override = default;
Robin Raymond22027b92018-11-23 14:07:5051
Danil Chapovalovfa52efa2019-02-21 10:13:5852 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 14:07:5056
Danil Chapovalovfa52efa2019-02-21 10:13:5857 private:
Robin Raymond22027b92018-11-23 14:07:5058 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 14:07:5076 NextTask GetNextTask();
77
Robin Raymond22027b92018-11-23 14:07:5078 void ProcessTasks();
79
80 void NotifyWake();
81
Robin Raymond22027b92018-11-23 14:07:5082 // Indicates if the thread has started.
Danil Chapovalovfa52efa2019-02-21 10:13:5883 rtc::Event started_;
Robin Raymond22027b92018-11-23 14:07:5084
Robin Raymond22027b92018-11-23 14:07:5085 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 10:13:5886 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 14:07:5087
Markus Handell18523c32020-07-08 15:55:5888 Mutex pending_lock_;
Robin Raymond22027b92018-11-23 14:07:5089
90 // Indicates if the worker thread needs to shutdown now.
91 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_){false};
92
93 // Holds the next order to use for the next task to be
94 // put into one of the pending queues.
95 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_){};
96
97 // The list of all pending tasks that need to be processed in the
98 // FIFO queue ordering on the worker thread.
99 std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
100 RTC_GUARDED_BY(pending_lock_);
101
102 // The list of all pending tasks that need to be processed at a future
103 // time based upon a delay. On the off change the delayed task should
104 // happen at exactly the same time interval as another task then the
105 // task is processed based on FIFO ordering. std::priority_queue was
106 // considered but rejected due to its inability to extract the
107 // std::unique_ptr out of the queue without the presence of a hack.
108 std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
109 RTC_GUARDED_BY(pending_lock_);
Markus Handell49cb4592021-06-22 08:02:26110
111 // Contains the active worker thread assigned to processing
112 // tasks (including delayed tasks).
113 // Placing this last ensures the thread doesn't touch uninitialized attributes
114 // throughout it's lifetime.
115 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 14:07:50116};
117
Danil Chapovalovfa52efa2019-02-21 10:13:58118TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
119 rtc::ThreadPriority priority)
120 : started_(/*manual_reset=*/false, /*initially_signaled=*/false),
Robin Raymond22027b92018-11-23 14:07:50121 flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
Markus Handellad5037b2021-05-07 13:02:36122 thread_(rtc::PlatformThread::SpawnJoinable(
123 [this] {
124 CurrentTaskQueueSetter set_current(this);
125 ProcessTasks();
126 },
127 queue_name,
128 rtc::ThreadAttributes().SetPriority(priority))) {
Danil Chapovalovfa52efa2019-02-21 10:13:58129 started_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 14:07:50130}
131
Danil Chapovalovfa52efa2019-02-21 10:13:58132void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 14:07:50133 RTC_DCHECK(!IsCurrent());
134
135 {
Markus Handell18523c32020-07-08 15:55:58136 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50137 thread_should_quit_ = true;
138 }
139
140 NotifyWake();
141
Danil Chapovalovfa52efa2019-02-21 10:13:58142 delete this;
Robin Raymond22027b92018-11-23 14:07:50143}
144
Danil Chapovalovfa52efa2019-02-21 10:13:58145void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
Robin Raymond22027b92018-11-23 14:07:50146 {
Markus Handell18523c32020-07-08 15:55:58147 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50148 OrderId order = thread_posting_order_++;
149
150 pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
151 order, std::move(task)));
152 }
153
154 NotifyWake();
155}
156
Danil Chapovalovfa52efa2019-02-21 10:13:58157void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
Robin Raymond22027b92018-11-23 14:07:50158 uint32_t milliseconds) {
159 auto fire_at = rtc::TimeMillis() + milliseconds;
160
161 DelayedEntryTimeout delay;
162 delay.next_fire_at_ms_ = fire_at;
163
164 {
Markus Handell18523c32020-07-08 15:55:58165 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50166 delay.order_ = ++thread_posting_order_;
167 delayed_queue_[delay] = std::move(task);
168 }
169
170 NotifyWake();
171}
172
Danil Chapovalovfa52efa2019-02-21 10:13:58173TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Robin Raymond22027b92018-11-23 14:07:50174 NextTask result{};
175
176 auto tick = rtc::TimeMillis();
177
Markus Handell18523c32020-07-08 15:55:58178 MutexLock lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50179
180 if (thread_should_quit_) {
181 result.final_task_ = true;
182 return result;
183 }
184
185 if (delayed_queue_.size() > 0) {
186 auto delayed_entry = delayed_queue_.begin();
187 const auto& delay_info = delayed_entry->first;
188 auto& delay_run = delayed_entry->second;
189 if (tick >= delay_info.next_fire_at_ms_) {
190 if (pending_queue_.size() > 0) {
191 auto& entry = pending_queue_.front();
192 auto& entry_order = entry.first;
193 auto& entry_run = entry.second;
194 if (entry_order < delay_info.order_) {
195 result.run_task_ = std::move(entry_run);
196 pending_queue_.pop();
197 return result;
198 }
199 }
200
201 result.run_task_ = std::move(delay_run);
202 delayed_queue_.erase(delayed_entry);
203 return result;
204 }
205
206 result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
207 }
208
209 if (pending_queue_.size() > 0) {
210 auto& entry = pending_queue_.front();
211 result.run_task_ = std::move(entry.second);
212 pending_queue_.pop();
213 }
214
215 return result;
216}
217
Danil Chapovalovfa52efa2019-02-21 10:13:58218void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 14:07:50219 started_.Set();
220
221 while (true) {
222 auto task = GetNextTask();
223
224 if (task.final_task_)
225 break;
226
227 if (task.run_task_) {
228 // process entry immediately then try again
229 QueuedTask* release_ptr = task.run_task_.release();
230 if (release_ptr->Run())
231 delete release_ptr;
232
233 // attempt to sleep again
234 continue;
235 }
236
237 if (0 == task.sleep_time_ms_)
Danil Chapovalovfa52efa2019-02-21 10:13:58238 flag_notify_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 14:07:50239 else
240 flag_notify_.Wait(task.sleep_time_ms_);
241 }
Robin Raymond22027b92018-11-23 14:07:50242}
243
Danil Chapovalovfa52efa2019-02-21 10:13:58244void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 14:07:50245 // The queue holds pending tasks to complete. Either tasks are to be
246 // executed immediately or tasks are to be run at some future delayed time.
247 // For immediate tasks the task queue's thread is busy running the task and
248 // the thread will not be waiting on the flag_notify_ event. If no immediate
249 // tasks are available but a delayed task is pending then the thread will be
250 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
251 // to run. If no immediate or pending tasks are available, the thread will
252 // wait on flag_notify_ until signaled that a task has been added (or the
253 // thread to be told to shutdown).
254
255 // In all cases, when a new immediate task, delayed task, or request to
256 // shutdown the thread is added the flag_notify_ is signaled after. If the
257 // thread was waiting then the thread will wake up immediately and re-assess
258 // what task needs to be run next (i.e. run a task now, wait for the nearest
259 // timed delayed task, or shutdown the thread). If the thread was not waiting
260 // then the thread will remained signaled to wake up the next time any
261 // attempt to wait on the flag_notify_ event occurs.
262
263 // Any immediate or delayed pending task (or request to shutdown the thread)
264 // must always be added to the queue prior to signaling flag_notify_ to wake
265 // up the possibly sleeping thread. This prevents a race condition where the
266 // thread is notified to wake up but the task queue's thread finds nothing to
267 // do so it waits once again to be signaled where such a signal may never
268 // happen.
269 flag_notify_.Set();
270}
271
Danil Chapovalovfa52efa2019-02-21 10:13:58272class TaskQueueStdlibFactory final : public TaskQueueFactory {
273 public:
274 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
275 absl::string_view name,
276 Priority priority) const override {
277 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
278 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
279 }
280};
281
282} // namespace
283
284std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
Mirko Bonadei317a1f02019-09-17 15:06:18285 return std::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 14:07:50286}
287
Danil Chapovalovfa52efa2019-02-21 10:13:58288} // namespace webrtc