blob: c1e7c4621c81e27de595dd9ccc548095eafc009d [file] [log] [blame]
tommic06b1332016-05-14 11:31:40 -07001/*
2 * Copyright 2016 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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/task_queue.h"
tommic06b1332016-05-14 11:31:40 -070012
Yves Gerey665174f2018-06-19 15:03:05 +020013// clang-format off
14// clang formating would change include order.
15
Danil Chapovalov02fddf62018-02-12 12:41:16 +010016// Include winsock2.h before including <windows.h> to maintain consistency with
Niels Möllerb06b0a62018-05-25 10:05:34 +020017// win32.h. To include win32.h directly, it must be broken out into its own
18// build target.
Danil Chapovalov02fddf62018-02-12 12:41:16 +010019#include <winsock2.h>
20#include <windows.h>
Yves Gerey665174f2018-06-19 15:03:05 +020021#include <sal.h> // Must come after windows headers.
Danil Chapovalov02fddf62018-02-12 12:41:16 +010022#include <mmsystem.h> // Must come after windows headers.
Yves Gerey665174f2018-06-19 15:03:05 +020023// clang-format on
tommic06b1332016-05-14 11:31:40 -070024#include <string.h>
tommic06b1332016-05-14 11:31:40 -070025
tommif9d91542017-02-17 02:47:11 -080026#include <algorithm>
tommi0b942152017-03-10 09:33:53 -080027#include <queue>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020028#include <utility>
tommif9d91542017-02-17 02:47:11 -080029
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/arraysize.h"
31#include "rtc_base/checks.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010032#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/event.h"
34#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010035#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/platform_thread.h"
37#include "rtc_base/refcount.h"
38#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "rtc_base/timeutils.h"
tommic06b1332016-05-14 11:31:40 -070040
41namespace rtc {
42namespace {
43#define WM_RUN_TASK WM_USER + 1
44#define WM_QUEUE_DELAYED_TASK WM_USER + 2
45
tommic9bb7912017-02-24 10:42:14 -080046using Priority = TaskQueue::Priority;
47
tommic06b1332016-05-14 11:31:40 -070048DWORD g_queue_ptr_tls = 0;
49
50BOOL CALLBACK InitializeTls(PINIT_ONCE init_once, void* param, void** context) {
51 g_queue_ptr_tls = TlsAlloc();
52 return TRUE;
53}
54
55DWORD GetQueuePtrTls() {
56 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
tommif9d91542017-02-17 02:47:11 -080057 ::InitOnceExecuteOnce(&init_once, InitializeTls, nullptr, nullptr);
tommic06b1332016-05-14 11:31:40 -070058 return g_queue_ptr_tls;
59}
60
61struct ThreadStartupData {
62 Event* started;
63 void* thread_context;
64};
65
66void CALLBACK InitializeQueueThread(ULONG_PTR param) {
67 MSG msg;
tommif9d91542017-02-17 02:47:11 -080068 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
tommic06b1332016-05-14 11:31:40 -070069 ThreadStartupData* data = reinterpret_cast<ThreadStartupData*>(param);
tommif9d91542017-02-17 02:47:11 -080070 ::TlsSetValue(GetQueuePtrTls(), data->thread_context);
tommic06b1332016-05-14 11:31:40 -070071 data->started->Set();
72}
tommic9bb7912017-02-24 10:42:14 -080073
74ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
75 switch (priority) {
76 case Priority::HIGH:
77 return kRealtimePriority;
78 case Priority::LOW:
79 return kLowPriority;
80 case Priority::NORMAL:
81 return kNormalPriority;
82 default:
83 RTC_NOTREACHED();
84 break;
85 }
86 return kNormalPriority;
87}
tommi5bdee472017-03-03 05:20:12 -080088
tommi0b942152017-03-10 09:33:53 -080089int64_t GetTick() {
tommi5bdee472017-03-03 05:20:12 -080090 static const UINT kPeriod = 1;
91 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR);
tommi0b942152017-03-10 09:33:53 -080092 int64_t ret = TimeMillis();
tommi5bdee472017-03-03 05:20:12 -080093 if (high_res)
94 timeEndPeriod(kPeriod);
95 return ret;
96}
tommic06b1332016-05-14 11:31:40 -070097
tommi0b942152017-03-10 09:33:53 -080098class DelayedTaskInfo {
tommif9d91542017-02-17 02:47:11 -080099 public:
tommi0b942152017-03-10 09:33:53 -0800100 // Default ctor needed to support priority_queue::pop().
101 DelayedTaskInfo() {}
102 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task)
103 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {}
104 DelayedTaskInfo(DelayedTaskInfo&&) = default;
tommif9d91542017-02-17 02:47:11 -0800105
tommi0b942152017-03-10 09:33:53 -0800106 // Implement for priority_queue.
107 bool operator>(const DelayedTaskInfo& other) const {
108 return due_time_ > other.due_time_;
109 }
tommif9d91542017-02-17 02:47:11 -0800110
tommi0b942152017-03-10 09:33:53 -0800111 // Required by priority_queue::pop().
112 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default;
113
114 // See below for why this method is const.
115 void Run() const {
116 RTC_DCHECK(due_time_);
117 task_->Run() ? task_.reset() : static_cast<void>(task_.release());
118 }
119
120 int64_t due_time() const { return due_time_; }
121
122 private:
123 int64_t due_time_ = 0; // Absolute timestamp in milliseconds.
124
125 // |task| needs to be mutable because std::priority_queue::top() returns
126 // a const reference and a key in an ordered queue must not be changed.
127 // There are two basic workarounds, one using const_cast, which would also
128 // make the key (|due_time|), non-const and the other is to make the non-key
129 // (|task|), mutable.
130 // Because of this, the |task| variable is made private and can only be
131 // mutated by calling the |Run()| method.
132 mutable std::unique_ptr<QueuedTask> task_;
133};
134
135class MultimediaTimer {
136 public:
tommi83722262017-03-15 04:36:29 -0700137 // Note: We create an event that requires manual reset.
138 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {}
tommif9d91542017-02-17 02:47:11 -0800139
tommi0b942152017-03-10 09:33:53 -0800140 ~MultimediaTimer() {
141 Cancel();
142 ::CloseHandle(event_);
tommif9d91542017-02-17 02:47:11 -0800143 }
144
tommi0b942152017-03-10 09:33:53 -0800145 bool StartOneShotTimer(UINT delay_ms) {
tommif9d91542017-02-17 02:47:11 -0800146 RTC_DCHECK_EQ(0, timer_id_);
147 RTC_DCHECK(event_ != nullptr);
tommif9d91542017-02-17 02:47:11 -0800148 timer_id_ =
149 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0,
150 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
151 return timer_id_ != 0;
152 }
153
tommi0b942152017-03-10 09:33:53 -0800154 void Cancel() {
tommi83722262017-03-15 04:36:29 -0700155 ::ResetEvent(event_);
tommif9d91542017-02-17 02:47:11 -0800156 if (timer_id_) {
157 ::timeKillEvent(timer_id_);
158 timer_id_ = 0;
159 }
tommif9d91542017-02-17 02:47:11 -0800160 }
161
tommi0b942152017-03-10 09:33:53 -0800162 HANDLE* event_for_wait() { return &event_; }
tommif9d91542017-02-17 02:47:11 -0800163
164 private:
tommif9d91542017-02-17 02:47:11 -0800165 HANDLE event_ = nullptr;
166 MMRESULT timer_id_ = 0;
tommif9d91542017-02-17 02:47:11 -0800167
168 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer);
169};
170
tommi0b942152017-03-10 09:33:53 -0800171} // namespace
172
nisse341c8e42017-09-06 04:38:22 -0700173class TaskQueue::Impl : public RefCountInterface {
tommi0b942152017-03-10 09:33:53 -0800174 public:
nisse341c8e42017-09-06 04:38:22 -0700175 Impl(const char* queue_name, TaskQueue* queue, Priority priority);
176 ~Impl() override;
tommi0b942152017-03-10 09:33:53 -0800177
nisse341c8e42017-09-06 04:38:22 -0700178 static TaskQueue::Impl* Current();
179 static TaskQueue* CurrentQueue();
180
181 // Used for DCHECKing the current queue.
182 bool IsCurrent() const;
183
184 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200185 typename std::enable_if<!std::is_convertible<
186 Closure,
187 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
188 void PostTask(Closure&& closure) {
189 PostTask(NewClosure(std::forward<Closure>(closure)));
nisse341c8e42017-09-06 04:38:22 -0700190 }
191
192 void PostTask(std::unique_ptr<QueuedTask> task);
193 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
194 std::unique_ptr<QueuedTask> reply,
195 TaskQueue::Impl* reply_queue);
196
197 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
198
199 void RunPendingTasks();
tommi0b942152017-03-10 09:33:53 -0800200
201 private:
nisse341c8e42017-09-06 04:38:22 -0700202 static void ThreadMain(void* context);
tommi0b942152017-03-10 09:33:53 -0800203
nisse341c8e42017-09-06 04:38:22 -0700204 class WorkerThread : public PlatformThread {
205 public:
206 WorkerThread(ThreadRunFunction func,
207 void* obj,
208 const char* thread_name,
209 ThreadPriority priority)
210 : PlatformThread(func, obj, thread_name, priority) {}
211
212 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
213 return PlatformThread::QueueAPC(apc_function, data);
214 }
tommi0b942152017-03-10 09:33:53 -0800215 };
216
nisse341c8e42017-09-06 04:38:22 -0700217 class ThreadState {
218 public:
219 explicit ThreadState(HANDLE in_queue) : in_queue_(in_queue) {}
220 ~ThreadState() {}
221
222 void RunThreadMain();
223
224 private:
225 bool ProcessQueuedMessages();
226 void RunDueTasks();
227 void ScheduleNextTimer();
228 void CancelTimers();
229
230 // Since priority_queue<> by defult orders items in terms of
231 // largest->smallest, using std::less<>, and we want smallest->largest,
232 // we would like to use std::greater<> here. Alas it's only available in
233 // C++14 and later, so we roll our own compare template that that relies on
234 // operator<().
235 template <typename T>
236 struct greater {
237 bool operator()(const T& l, const T& r) { return l > r; }
238 };
239
240 MultimediaTimer timer_;
241 std::priority_queue<DelayedTaskInfo,
242 std::vector<DelayedTaskInfo>,
243 greater<DelayedTaskInfo>>
244 timer_tasks_;
245 UINT_PTR timer_id_ = 0;
246 HANDLE in_queue_;
247 };
248
249 TaskQueue* const queue_;
250 WorkerThread thread_;
251 rtc::CriticalSection pending_lock_;
danilchapa37de392017-09-09 04:17:22 -0700252 std::queue<std::unique_ptr<QueuedTask>> pending_
253 RTC_GUARDED_BY(pending_lock_);
tommi83722262017-03-15 04:36:29 -0700254 HANDLE in_queue_;
tommi0b942152017-03-10 09:33:53 -0800255};
256
nisse341c8e42017-09-06 04:38:22 -0700257TaskQueue::Impl::Impl(const char* queue_name,
258 TaskQueue* queue,
259 Priority priority)
260 : queue_(queue),
261 thread_(&TaskQueue::Impl::ThreadMain,
tommic9bb7912017-02-24 10:42:14 -0800262 this,
263 queue_name,
tommi83722262017-03-15 04:36:29 -0700264 TaskQueuePriorityToThreadPriority(priority)),
nisse341c8e42017-09-06 04:38:22 -0700265 in_queue_(::CreateEvent(nullptr, true, false, nullptr)) {
tommic06b1332016-05-14 11:31:40 -0700266 RTC_DCHECK(queue_name);
tommi83722262017-03-15 04:36:29 -0700267 RTC_DCHECK(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700268 thread_.Start();
269 Event event(false, false);
270 ThreadStartupData startup = {&event, this};
271 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread,
272 reinterpret_cast<ULONG_PTR>(&startup)));
273 event.Wait(Event::kForever);
274}
275
nisse341c8e42017-09-06 04:38:22 -0700276TaskQueue::Impl::~Impl() {
tommic06b1332016-05-14 11:31:40 -0700277 RTC_DCHECK(!IsCurrent());
tommif9d91542017-02-17 02:47:11 -0800278 while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) {
kwiberg352444f2016-11-28 15:58:53 -0800279 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError());
tommic06b1332016-05-14 11:31:40 -0700280 Sleep(1);
281 }
282 thread_.Stop();
tommi83722262017-03-15 04:36:29 -0700283 ::CloseHandle(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700284}
285
286// static
nisse341c8e42017-09-06 04:38:22 -0700287TaskQueue::Impl* TaskQueue::Impl::Current() {
288 return static_cast<TaskQueue::Impl*>(::TlsGetValue(GetQueuePtrTls()));
tommic06b1332016-05-14 11:31:40 -0700289}
290
nisse341c8e42017-09-06 04:38:22 -0700291// static
292TaskQueue* TaskQueue::Impl::CurrentQueue() {
293 TaskQueue::Impl* current = Current();
294 return current ? current->queue_ : nullptr;
295}
296
297bool TaskQueue::Impl::IsCurrent() const {
tommic06b1332016-05-14 11:31:40 -0700298 return IsThreadRefEqual(thread_.GetThreadRef(), CurrentThreadRef());
299}
300
nisse341c8e42017-09-06 04:38:22 -0700301void TaskQueue::Impl::PostTask(std::unique_ptr<QueuedTask> task) {
tommi83722262017-03-15 04:36:29 -0700302 rtc::CritScope lock(&pending_lock_);
303 pending_.push(std::move(task));
304 ::SetEvent(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700305}
306
nisse341c8e42017-09-06 04:38:22 -0700307void TaskQueue::Impl::PostDelayedTask(std::unique_ptr<QueuedTask> task,
308 uint32_t milliseconds) {
tommi0b942152017-03-10 09:33:53 -0800309 if (!milliseconds) {
310 PostTask(std::move(task));
311 return;
312 }
313
314 // TODO(tommi): Avoid this allocation. It is currently here since
315 // the timestamp stored in the task info object, is a 64bit timestamp
316 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the
317 // task pointer and timestamp as LPARAM and WPARAM.
318 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task));
319 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0,
320 reinterpret_cast<LPARAM>(task_info))) {
321 delete task_info;
tommic06b1332016-05-14 11:31:40 -0700322 }
323}
324
nisse341c8e42017-09-06 04:38:22 -0700325void TaskQueue::Impl::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
326 std::unique_ptr<QueuedTask> reply,
327 TaskQueue::Impl* reply_queue) {
tommic06b1332016-05-14 11:31:40 -0700328 QueuedTask* task_ptr = task.release();
329 QueuedTask* reply_task_ptr = reply.release();
330 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef();
331 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() {
332 if (task_ptr->Run())
333 delete task_ptr;
334 // If the thread's message queue is full, we can't queue the task and will
335 // have to drop it (i.e. delete).
tommif9d91542017-02-17 02:47:11 -0800336 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0,
337 reinterpret_cast<LPARAM>(reply_task_ptr))) {
tommic06b1332016-05-14 11:31:40 -0700338 delete reply_task_ptr;
339 }
340 });
341}
342
nisse341c8e42017-09-06 04:38:22 -0700343void TaskQueue::Impl::RunPendingTasks() {
tommi83722262017-03-15 04:36:29 -0700344 while (true) {
345 std::unique_ptr<QueuedTask> task;
346 {
347 rtc::CritScope lock(&pending_lock_);
348 if (pending_.empty())
349 break;
350 task = std::move(pending_.front());
351 pending_.pop();
352 }
353
354 if (!task->Run())
355 task.release();
356 }
357}
358
tommic06b1332016-05-14 11:31:40 -0700359// static
nisse341c8e42017-09-06 04:38:22 -0700360void TaskQueue::Impl::ThreadMain(void* context) {
361 ThreadState state(static_cast<TaskQueue::Impl*>(context)->in_queue_);
tommi0b942152017-03-10 09:33:53 -0800362 state.RunThreadMain();
363}
tommif9d91542017-02-17 02:47:11 -0800364
nisse341c8e42017-09-06 04:38:22 -0700365void TaskQueue::Impl::ThreadState::RunThreadMain() {
Yves Gerey665174f2018-06-19 15:03:05 +0200366 HANDLE handles[2] = {*timer_.event_for_wait(), in_queue_};
tommib89257a2016-07-12 01:24:36 -0700367 while (true) {
tommif9d91542017-02-17 02:47:11 -0800368 // Make sure we do an alertable wait as that's required to allow APCs to run
369 // (e.g. required for InitializeQueueThread and stopping the thread in
370 // PlatformThread).
tommi0b942152017-03-10 09:33:53 -0800371 DWORD result = ::MsgWaitForMultipleObjectsEx(
tommi83722262017-03-15 04:36:29 -0700372 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE);
tommib89257a2016-07-12 01:24:36 -0700373 RTC_CHECK_NE(WAIT_FAILED, result);
tommi83722262017-03-15 04:36:29 -0700374 if (result == (WAIT_OBJECT_0 + 2)) {
tommi0b942152017-03-10 09:33:53 -0800375 // There are messages in the message queue that need to be handled.
376 if (!ProcessQueuedMessages())
tommib89257a2016-07-12 01:24:36 -0700377 break;
tommi83722262017-03-15 04:36:29 -0700378 }
379
Yves Gerey665174f2018-06-19 15:03:05 +0200380 if (result == WAIT_OBJECT_0 ||
381 (!timer_tasks_.empty() &&
382 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) {
tommi0b942152017-03-10 09:33:53 -0800383 // The multimedia timer was signaled.
384 timer_.Cancel();
tommi0b942152017-03-10 09:33:53 -0800385 RunDueTasks();
386 ScheduleNextTimer();
tommi83722262017-03-15 04:36:29 -0700387 }
388
389 if (result == (WAIT_OBJECT_0 + 1)) {
390 ::ResetEvent(in_queue_);
nisse341c8e42017-09-06 04:38:22 -0700391 TaskQueue::Impl::Current()->RunPendingTasks();
tommib89257a2016-07-12 01:24:36 -0700392 }
393 }
tommib89257a2016-07-12 01:24:36 -0700394}
tommic06b1332016-05-14 11:31:40 -0700395
nisse341c8e42017-09-06 04:38:22 -0700396bool TaskQueue::Impl::ThreadState::ProcessQueuedMessages() {
tommib89257a2016-07-12 01:24:36 -0700397 MSG msg = {};
tommi83722262017-03-15 04:36:29 -0700398 // To protect against overly busy message queues, we limit the time
399 // we process tasks to a few milliseconds. If we don't do that, there's
400 // a chance that timer tasks won't ever run.
401 static const int kMaxTaskProcessingTimeMs = 500;
402 auto start = GetTick();
tommif9d91542017-02-17 02:47:11 -0800403 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) &&
tommib89257a2016-07-12 01:24:36 -0700404 msg.message != WM_QUIT) {
tommic06b1332016-05-14 11:31:40 -0700405 if (!msg.hwnd) {
406 switch (msg.message) {
tommi83722262017-03-15 04:36:29 -0700407 // TODO(tommi): Stop using this way of queueing tasks.
tommic06b1332016-05-14 11:31:40 -0700408 case WM_RUN_TASK: {
409 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam);
410 if (task->Run())
411 delete task;
412 break;
413 }
414 case WM_QUEUE_DELAYED_TASK: {
tommi0b942152017-03-10 09:33:53 -0800415 std::unique_ptr<DelayedTaskInfo> info(
416 reinterpret_cast<DelayedTaskInfo*>(msg.lParam));
417 bool need_to_schedule_timers =
418 timer_tasks_.empty() ||
419 timer_tasks_.top().due_time() > info->due_time();
420 timer_tasks_.emplace(std::move(*info.get()));
421 if (need_to_schedule_timers) {
422 CancelTimers();
423 ScheduleNextTimer();
tommif9d91542017-02-17 02:47:11 -0800424 }
tommic06b1332016-05-14 11:31:40 -0700425 break;
426 }
427 case WM_TIMER: {
tommi0b942152017-03-10 09:33:53 -0800428 RTC_DCHECK_EQ(timer_id_, msg.wParam);
tommif9d91542017-02-17 02:47:11 -0800429 ::KillTimer(nullptr, msg.wParam);
tommi0b942152017-03-10 09:33:53 -0800430 timer_id_ = 0;
431 RunDueTasks();
432 ScheduleNextTimer();
tommic06b1332016-05-14 11:31:40 -0700433 break;
434 }
435 default:
436 RTC_NOTREACHED();
437 break;
438 }
439 } else {
tommif9d91542017-02-17 02:47:11 -0800440 ::TranslateMessage(&msg);
441 ::DispatchMessage(&msg);
tommic06b1332016-05-14 11:31:40 -0700442 }
tommi83722262017-03-15 04:36:29 -0700443
444 if (GetTick() > start + kMaxTaskProcessingTimeMs)
445 break;
tommic06b1332016-05-14 11:31:40 -0700446 }
tommib89257a2016-07-12 01:24:36 -0700447 return msg.message != WM_QUIT;
tommic06b1332016-05-14 11:31:40 -0700448}
tommib89257a2016-07-12 01:24:36 -0700449
nisse341c8e42017-09-06 04:38:22 -0700450void TaskQueue::Impl::ThreadState::RunDueTasks() {
tommi0b942152017-03-10 09:33:53 -0800451 RTC_DCHECK(!timer_tasks_.empty());
452 auto now = GetTick();
453 do {
454 const auto& top = timer_tasks_.top();
455 if (top.due_time() > now)
456 break;
457 top.Run();
458 timer_tasks_.pop();
459 } while (!timer_tasks_.empty());
460}
461
nisse341c8e42017-09-06 04:38:22 -0700462void TaskQueue::Impl::ThreadState::ScheduleNextTimer() {
tommi0b942152017-03-10 09:33:53 -0800463 RTC_DCHECK_EQ(timer_id_, 0);
464 if (timer_tasks_.empty())
465 return;
466
467 const auto& next_task = timer_tasks_.top();
468 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick());
469 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms);
470 if (!timer_.StartOneShotTimer(milliseconds))
471 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr);
472}
473
nisse341c8e42017-09-06 04:38:22 -0700474void TaskQueue::Impl::ThreadState::CancelTimers() {
tommi0b942152017-03-10 09:33:53 -0800475 timer_.Cancel();
476 if (timer_id_) {
477 ::KillTimer(nullptr, timer_id_);
478 timer_id_ = 0;
479 }
480}
481
nisse341c8e42017-09-06 04:38:22 -0700482// Boilerplate for the PIMPL pattern.
483TaskQueue::TaskQueue(const char* queue_name, Priority priority)
484 : impl_(new RefCountedObject<TaskQueue::Impl>(queue_name, this, priority)) {
485}
486
487TaskQueue::~TaskQueue() {}
488
489// static
490TaskQueue* TaskQueue::Current() {
491 return TaskQueue::Impl::CurrentQueue();
492}
493
494// Used for DCHECKing the current queue.
495bool TaskQueue::IsCurrent() const {
496 return impl_->IsCurrent();
497}
498
499void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) {
500 return TaskQueue::impl_->PostTask(std::move(task));
501}
502
503void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
504 std::unique_ptr<QueuedTask> reply,
505 TaskQueue* reply_queue) {
506 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
507 reply_queue->impl_.get());
508}
509
510void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
511 std::unique_ptr<QueuedTask> reply) {
512 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
513 impl_.get());
514}
515
516void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task,
517 uint32_t milliseconds) {
518 return TaskQueue::impl_->PostDelayedTask(std::move(task), milliseconds);
519}
520
tommic06b1332016-05-14 11:31:40 -0700521} // namespace rtc