blob: 88128b5c568fbc232a882d23d598ddab4ec52df5 [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>
14#include <algorithm>
Robin Raymond22027b92018-11-23 14:07:5015#include <map>
16#include <queue>
17#include <utility>
18
Danil Chapovalovfa52efa2019-02-21 10:13:5819#include "absl/memory/memory.h"
20#include "absl/strings/string_view.h"
21#include "api/task_queue/queued_task.h"
22#include "api/task_queue/task_queue_base.h"
Robin Raymond22027b92018-11-23 14:07:5023#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 17:11:0024#include "rtc_base/critical_section.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"
Robin Raymond22027b92018-11-23 14:07:5028#include "rtc_base/thread_annotations.h"
Steve Anton10542f22019-01-11 17:11:0029#include "rtc_base/time_utils.h"
Robin Raymond22027b92018-11-23 14:07:5030
Danil Chapovalovfa52efa2019-02-21 10:13:5831namespace webrtc {
Robin Raymond22027b92018-11-23 14:07:5032namespace {
33
Danil Chapovalovfa52efa2019-02-21 10:13:5834rtc::ThreadPriority TaskQueuePriorityToThreadPriority(
35 TaskQueueFactory::Priority priority) {
Robin Raymond22027b92018-11-23 14:07:5036 switch (priority) {
Danil Chapovalovfa52efa2019-02-21 10:13:5837 case TaskQueueFactory::Priority::HIGH:
38 return rtc::kRealtimePriority;
39 case TaskQueueFactory::Priority::LOW:
40 return rtc::kLowPriority;
41 case TaskQueueFactory::Priority::NORMAL:
42 return rtc::kNormalPriority;
Robin Raymond22027b92018-11-23 14:07:5043 default:
44 RTC_NOTREACHED();
Danil Chapovalovfa52efa2019-02-21 10:13:5845 return rtc::kNormalPriority;
Robin Raymond22027b92018-11-23 14:07:5046 }
Robin Raymond22027b92018-11-23 14:07:5047}
48
Danil Chapovalovfa52efa2019-02-21 10:13:5849class TaskQueueStdlib final : public TaskQueueBase {
Robin Raymond22027b92018-11-23 14:07:5050 public:
Danil Chapovalovfa52efa2019-02-21 10:13:5851 TaskQueueStdlib(absl::string_view queue_name, rtc::ThreadPriority priority);
52 ~TaskQueueStdlib() override = default;
Robin Raymond22027b92018-11-23 14:07:5053
Danil Chapovalovfa52efa2019-02-21 10:13:5854 void Delete() override;
55 void PostTask(std::unique_ptr<QueuedTask> task) override;
56 void PostDelayedTask(std::unique_ptr<QueuedTask> task,
57 uint32_t milliseconds) override;
Robin Raymond22027b92018-11-23 14:07:5058
Danil Chapovalovfa52efa2019-02-21 10:13:5859 private:
Robin Raymond22027b92018-11-23 14:07:5060 using OrderId = uint64_t;
61
62 struct DelayedEntryTimeout {
63 int64_t next_fire_at_ms_{};
64 OrderId order_{};
65
66 bool operator<(const DelayedEntryTimeout& o) const {
67 return std::tie(next_fire_at_ms_, order_) <
68 std::tie(o.next_fire_at_ms_, o.order_);
69 }
70 };
71
72 struct NextTask {
73 bool final_task_{false};
74 std::unique_ptr<QueuedTask> run_task_;
75 int64_t sleep_time_ms_{};
76 };
77
Robin Raymond22027b92018-11-23 14:07:5078 NextTask GetNextTask();
79
Robin Raymond22027b92018-11-23 14:07:5080 static void ThreadMain(void* context);
81
82 void ProcessTasks();
83
84 void NotifyWake();
85
Robin Raymond22027b92018-11-23 14:07:5086 // Indicates if the thread has started.
Danil Chapovalovfa52efa2019-02-21 10:13:5887 rtc::Event started_;
Robin Raymond22027b92018-11-23 14:07:5088
89 // Indicates if the thread has stopped.
Danil Chapovalovfa52efa2019-02-21 10:13:5890 rtc::Event stopped_;
Robin Raymond22027b92018-11-23 14:07:5091
92 // Signaled whenever a new task is pending.
Danil Chapovalovfa52efa2019-02-21 10:13:5893 rtc::Event flag_notify_;
Robin Raymond22027b92018-11-23 14:07:5094
95 // Contains the active worker thread assigned to processing
96 // tasks (including delayed tasks).
Danil Chapovalovfa52efa2019-02-21 10:13:5897 rtc::PlatformThread thread_;
Robin Raymond22027b92018-11-23 14:07:5098
99 rtc::CriticalSection pending_lock_;
100
101 // Indicates if the worker thread needs to shutdown now.
102 bool thread_should_quit_ RTC_GUARDED_BY(pending_lock_){false};
103
104 // Holds the next order to use for the next task to be
105 // put into one of the pending queues.
106 OrderId thread_posting_order_ RTC_GUARDED_BY(pending_lock_){};
107
108 // The list of all pending tasks that need to be processed in the
109 // FIFO queue ordering on the worker thread.
110 std::queue<std::pair<OrderId, std::unique_ptr<QueuedTask>>> pending_queue_
111 RTC_GUARDED_BY(pending_lock_);
112
113 // The list of all pending tasks that need to be processed at a future
114 // time based upon a delay. On the off change the delayed task should
115 // happen at exactly the same time interval as another task then the
116 // task is processed based on FIFO ordering. std::priority_queue was
117 // considered but rejected due to its inability to extract the
118 // std::unique_ptr out of the queue without the presence of a hack.
119 std::map<DelayedEntryTimeout, std::unique_ptr<QueuedTask>> delayed_queue_
120 RTC_GUARDED_BY(pending_lock_);
121};
122
Danil Chapovalovfa52efa2019-02-21 10:13:58123TaskQueueStdlib::TaskQueueStdlib(absl::string_view queue_name,
124 rtc::ThreadPriority priority)
125 : started_(/*manual_reset=*/false, /*initially_signaled=*/false),
Robin Raymond22027b92018-11-23 14:07:50126 stopped_(/*manual_reset=*/false, /*initially_signaled=*/false),
127 flag_notify_(/*manual_reset=*/false, /*initially_signaled=*/false),
Danil Chapovalovfa52efa2019-02-21 10:13:58128 thread_(&TaskQueueStdlib::ThreadMain, this, queue_name, priority) {
Robin Raymond22027b92018-11-23 14:07:50129 thread_.Start();
Danil Chapovalovfa52efa2019-02-21 10:13:58130 started_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 14:07:50131}
132
Danil Chapovalovfa52efa2019-02-21 10:13:58133void TaskQueueStdlib::Delete() {
Robin Raymond22027b92018-11-23 14:07:50134 RTC_DCHECK(!IsCurrent());
135
136 {
Danil Chapovalovfa52efa2019-02-21 10:13:58137 rtc::CritScope lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50138 thread_should_quit_ = true;
139 }
140
141 NotifyWake();
142
Danil Chapovalovfa52efa2019-02-21 10:13:58143 stopped_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 14:07:50144 thread_.Stop();
Danil Chapovalovfa52efa2019-02-21 10:13:58145 delete this;
Robin Raymond22027b92018-11-23 14:07:50146}
147
Danil Chapovalovfa52efa2019-02-21 10:13:58148void TaskQueueStdlib::PostTask(std::unique_ptr<QueuedTask> task) {
Robin Raymond22027b92018-11-23 14:07:50149 {
Danil Chapovalovfa52efa2019-02-21 10:13:58150 rtc::CritScope lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50151 OrderId order = thread_posting_order_++;
152
153 pending_queue_.push(std::pair<OrderId, std::unique_ptr<QueuedTask>>(
154 order, std::move(task)));
155 }
156
157 NotifyWake();
158}
159
Danil Chapovalovfa52efa2019-02-21 10:13:58160void TaskQueueStdlib::PostDelayedTask(std::unique_ptr<QueuedTask> task,
Robin Raymond22027b92018-11-23 14:07:50161 uint32_t milliseconds) {
162 auto fire_at = rtc::TimeMillis() + milliseconds;
163
164 DelayedEntryTimeout delay;
165 delay.next_fire_at_ms_ = fire_at;
166
167 {
Danil Chapovalovfa52efa2019-02-21 10:13:58168 rtc::CritScope lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50169 delay.order_ = ++thread_posting_order_;
170 delayed_queue_[delay] = std::move(task);
171 }
172
173 NotifyWake();
174}
175
Danil Chapovalovfa52efa2019-02-21 10:13:58176TaskQueueStdlib::NextTask TaskQueueStdlib::GetNextTask() {
Robin Raymond22027b92018-11-23 14:07:50177 NextTask result{};
178
179 auto tick = rtc::TimeMillis();
180
Danil Chapovalovfa52efa2019-02-21 10:13:58181 rtc::CritScope lock(&pending_lock_);
Robin Raymond22027b92018-11-23 14:07:50182
183 if (thread_should_quit_) {
184 result.final_task_ = true;
185 return result;
186 }
187
188 if (delayed_queue_.size() > 0) {
189 auto delayed_entry = delayed_queue_.begin();
190 const auto& delay_info = delayed_entry->first;
191 auto& delay_run = delayed_entry->second;
192 if (tick >= delay_info.next_fire_at_ms_) {
193 if (pending_queue_.size() > 0) {
194 auto& entry = pending_queue_.front();
195 auto& entry_order = entry.first;
196 auto& entry_run = entry.second;
197 if (entry_order < delay_info.order_) {
198 result.run_task_ = std::move(entry_run);
199 pending_queue_.pop();
200 return result;
201 }
202 }
203
204 result.run_task_ = std::move(delay_run);
205 delayed_queue_.erase(delayed_entry);
206 return result;
207 }
208
209 result.sleep_time_ms_ = delay_info.next_fire_at_ms_ - tick;
210 }
211
212 if (pending_queue_.size() > 0) {
213 auto& entry = pending_queue_.front();
214 result.run_task_ = std::move(entry.second);
215 pending_queue_.pop();
216 }
217
218 return result;
219}
220
221// static
Danil Chapovalovfa52efa2019-02-21 10:13:58222void TaskQueueStdlib::ThreadMain(void* context) {
223 TaskQueueStdlib* me = static_cast<TaskQueueStdlib*>(context);
224 CurrentTaskQueueSetter set_current(me);
Robin Raymond22027b92018-11-23 14:07:50225 me->ProcessTasks();
226}
227
Danil Chapovalovfa52efa2019-02-21 10:13:58228void TaskQueueStdlib::ProcessTasks() {
Robin Raymond22027b92018-11-23 14:07:50229 started_.Set();
230
231 while (true) {
232 auto task = GetNextTask();
233
234 if (task.final_task_)
235 break;
236
237 if (task.run_task_) {
238 // process entry immediately then try again
239 QueuedTask* release_ptr = task.run_task_.release();
240 if (release_ptr->Run())
241 delete release_ptr;
242
243 // attempt to sleep again
244 continue;
245 }
246
247 if (0 == task.sleep_time_ms_)
Danil Chapovalovfa52efa2019-02-21 10:13:58248 flag_notify_.Wait(rtc::Event::kForever);
Robin Raymond22027b92018-11-23 14:07:50249 else
250 flag_notify_.Wait(task.sleep_time_ms_);
251 }
252
253 stopped_.Set();
254}
255
Danil Chapovalovfa52efa2019-02-21 10:13:58256void TaskQueueStdlib::NotifyWake() {
Robin Raymond22027b92018-11-23 14:07:50257 // The queue holds pending tasks to complete. Either tasks are to be
258 // executed immediately or tasks are to be run at some future delayed time.
259 // For immediate tasks the task queue's thread is busy running the task and
260 // the thread will not be waiting on the flag_notify_ event. If no immediate
261 // tasks are available but a delayed task is pending then the thread will be
262 // waiting on flag_notify_ with a delayed time-out of the nearest timed task
263 // to run. If no immediate or pending tasks are available, the thread will
264 // wait on flag_notify_ until signaled that a task has been added (or the
265 // thread to be told to shutdown).
266
267 // In all cases, when a new immediate task, delayed task, or request to
268 // shutdown the thread is added the flag_notify_ is signaled after. If the
269 // thread was waiting then the thread will wake up immediately and re-assess
270 // what task needs to be run next (i.e. run a task now, wait for the nearest
271 // timed delayed task, or shutdown the thread). If the thread was not waiting
272 // then the thread will remained signaled to wake up the next time any
273 // attempt to wait on the flag_notify_ event occurs.
274
275 // Any immediate or delayed pending task (or request to shutdown the thread)
276 // must always be added to the queue prior to signaling flag_notify_ to wake
277 // up the possibly sleeping thread. This prevents a race condition where the
278 // thread is notified to wake up but the task queue's thread finds nothing to
279 // do so it waits once again to be signaled where such a signal may never
280 // happen.
281 flag_notify_.Set();
282}
283
Danil Chapovalovfa52efa2019-02-21 10:13:58284class TaskQueueStdlibFactory final : public TaskQueueFactory {
285 public:
286 std::unique_ptr<TaskQueueBase, TaskQueueDeleter> CreateTaskQueue(
287 absl::string_view name,
288 Priority priority) const override {
289 return std::unique_ptr<TaskQueueBase, TaskQueueDeleter>(
290 new TaskQueueStdlib(name, TaskQueuePriorityToThreadPriority(priority)));
291 }
292};
293
294} // namespace
295
296std::unique_ptr<TaskQueueFactory> CreateTaskQueueStdlibFactory() {
297 return absl::make_unique<TaskQueueStdlibFactory>();
Robin Raymond22027b92018-11-23 14:07:50298}
299
Danil Chapovalovfa52efa2019-02-21 10:13:58300} // namespace webrtc