blob: cbf86a6a1139ed048345c5c04509284e9f4031c8 [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
Danil Chapovalov02fddf62018-02-12 12:41:16 +010013// Include winsock2.h before including <windows.h> to maintain consistency with
14// win32.h. We can't include win32.h directly here since it pulls in
15// headers such as basictypes.h which causes problems in Chromium where webrtc
16// exists as two separate projects, webrtc and libjingle.
17#include <winsock2.h>
18#include <windows.h>
19#include <sal.h> // Must come after windows headers.
20#include <mmsystem.h> // Must come after windows headers.
tommic06b1332016-05-14 11:31:40 -070021#include <string.h>
tommic06b1332016-05-14 11:31:40 -070022
tommif9d91542017-02-17 02:47:11 -080023#include <algorithm>
tommi0b942152017-03-10 09:33:53 -080024#include <queue>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020025#include <utility>
tommif9d91542017-02-17 02:47:11 -080026
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/arraysize.h"
28#include "rtc_base/checks.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010029#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/event.h"
31#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010032#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/platform_thread.h"
34#include "rtc_base/refcount.h"
35#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "rtc_base/timeutils.h"
tommic06b1332016-05-14 11:31:40 -070037
38namespace rtc {
39namespace {
40#define WM_RUN_TASK WM_USER + 1
41#define WM_QUEUE_DELAYED_TASK WM_USER + 2
42
tommic9bb7912017-02-24 10:42:14 -080043using Priority = TaskQueue::Priority;
44
tommic06b1332016-05-14 11:31:40 -070045DWORD g_queue_ptr_tls = 0;
46
47BOOL CALLBACK InitializeTls(PINIT_ONCE init_once, void* param, void** context) {
48 g_queue_ptr_tls = TlsAlloc();
49 return TRUE;
50}
51
52DWORD GetQueuePtrTls() {
53 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
tommif9d91542017-02-17 02:47:11 -080054 ::InitOnceExecuteOnce(&init_once, InitializeTls, nullptr, nullptr);
tommic06b1332016-05-14 11:31:40 -070055 return g_queue_ptr_tls;
56}
57
58struct ThreadStartupData {
59 Event* started;
60 void* thread_context;
61};
62
63void CALLBACK InitializeQueueThread(ULONG_PTR param) {
64 MSG msg;
tommif9d91542017-02-17 02:47:11 -080065 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
tommic06b1332016-05-14 11:31:40 -070066 ThreadStartupData* data = reinterpret_cast<ThreadStartupData*>(param);
tommif9d91542017-02-17 02:47:11 -080067 ::TlsSetValue(GetQueuePtrTls(), data->thread_context);
tommic06b1332016-05-14 11:31:40 -070068 data->started->Set();
69}
tommic9bb7912017-02-24 10:42:14 -080070
71ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
72 switch (priority) {
73 case Priority::HIGH:
74 return kRealtimePriority;
75 case Priority::LOW:
76 return kLowPriority;
77 case Priority::NORMAL:
78 return kNormalPriority;
79 default:
80 RTC_NOTREACHED();
81 break;
82 }
83 return kNormalPriority;
84}
tommi5bdee472017-03-03 05:20:12 -080085
tommi0b942152017-03-10 09:33:53 -080086int64_t GetTick() {
tommi5bdee472017-03-03 05:20:12 -080087 static const UINT kPeriod = 1;
88 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR);
tommi0b942152017-03-10 09:33:53 -080089 int64_t ret = TimeMillis();
tommi5bdee472017-03-03 05:20:12 -080090 if (high_res)
91 timeEndPeriod(kPeriod);
92 return ret;
93}
tommic06b1332016-05-14 11:31:40 -070094
tommi0b942152017-03-10 09:33:53 -080095class DelayedTaskInfo {
tommif9d91542017-02-17 02:47:11 -080096 public:
tommi0b942152017-03-10 09:33:53 -080097 // Default ctor needed to support priority_queue::pop().
98 DelayedTaskInfo() {}
99 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task)
100 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {}
101 DelayedTaskInfo(DelayedTaskInfo&&) = default;
tommif9d91542017-02-17 02:47:11 -0800102
tommi0b942152017-03-10 09:33:53 -0800103 // Implement for priority_queue.
104 bool operator>(const DelayedTaskInfo& other) const {
105 return due_time_ > other.due_time_;
106 }
tommif9d91542017-02-17 02:47:11 -0800107
tommi0b942152017-03-10 09:33:53 -0800108 // Required by priority_queue::pop().
109 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default;
110
111 // See below for why this method is const.
112 void Run() const {
113 RTC_DCHECK(due_time_);
114 task_->Run() ? task_.reset() : static_cast<void>(task_.release());
115 }
116
117 int64_t due_time() const { return due_time_; }
118
119 private:
120 int64_t due_time_ = 0; // Absolute timestamp in milliseconds.
121
122 // |task| needs to be mutable because std::priority_queue::top() returns
123 // a const reference and a key in an ordered queue must not be changed.
124 // There are two basic workarounds, one using const_cast, which would also
125 // make the key (|due_time|), non-const and the other is to make the non-key
126 // (|task|), mutable.
127 // Because of this, the |task| variable is made private and can only be
128 // mutated by calling the |Run()| method.
129 mutable std::unique_ptr<QueuedTask> task_;
130};
131
132class MultimediaTimer {
133 public:
tommi83722262017-03-15 04:36:29 -0700134 // Note: We create an event that requires manual reset.
135 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {}
tommif9d91542017-02-17 02:47:11 -0800136
tommi0b942152017-03-10 09:33:53 -0800137 ~MultimediaTimer() {
138 Cancel();
139 ::CloseHandle(event_);
tommif9d91542017-02-17 02:47:11 -0800140 }
141
tommi0b942152017-03-10 09:33:53 -0800142 bool StartOneShotTimer(UINT delay_ms) {
tommif9d91542017-02-17 02:47:11 -0800143 RTC_DCHECK_EQ(0, timer_id_);
144 RTC_DCHECK(event_ != nullptr);
tommif9d91542017-02-17 02:47:11 -0800145 timer_id_ =
146 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0,
147 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
148 return timer_id_ != 0;
149 }
150
tommi0b942152017-03-10 09:33:53 -0800151 void Cancel() {
tommi83722262017-03-15 04:36:29 -0700152 ::ResetEvent(event_);
tommif9d91542017-02-17 02:47:11 -0800153 if (timer_id_) {
154 ::timeKillEvent(timer_id_);
155 timer_id_ = 0;
156 }
tommif9d91542017-02-17 02:47:11 -0800157 }
158
tommi0b942152017-03-10 09:33:53 -0800159 HANDLE* event_for_wait() { return &event_; }
tommif9d91542017-02-17 02:47:11 -0800160
161 private:
tommif9d91542017-02-17 02:47:11 -0800162 HANDLE event_ = nullptr;
163 MMRESULT timer_id_ = 0;
tommif9d91542017-02-17 02:47:11 -0800164
165 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer);
166};
167
tommi0b942152017-03-10 09:33:53 -0800168} // namespace
169
nisse341c8e42017-09-06 04:38:22 -0700170class TaskQueue::Impl : public RefCountInterface {
tommi0b942152017-03-10 09:33:53 -0800171 public:
nisse341c8e42017-09-06 04:38:22 -0700172 Impl(const char* queue_name, TaskQueue* queue, Priority priority);
173 ~Impl() override;
tommi0b942152017-03-10 09:33:53 -0800174
nisse341c8e42017-09-06 04:38:22 -0700175 static TaskQueue::Impl* Current();
176 static TaskQueue* CurrentQueue();
177
178 // Used for DCHECKing the current queue.
179 bool IsCurrent() const;
180
181 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200182 typename std::enable_if<!std::is_convertible<
183 Closure,
184 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
185 void PostTask(Closure&& closure) {
186 PostTask(NewClosure(std::forward<Closure>(closure)));
nisse341c8e42017-09-06 04:38:22 -0700187 }
188
189 void PostTask(std::unique_ptr<QueuedTask> task);
190 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
191 std::unique_ptr<QueuedTask> reply,
192 TaskQueue::Impl* reply_queue);
193
194 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
195
196 void RunPendingTasks();
tommi0b942152017-03-10 09:33:53 -0800197
198 private:
nisse341c8e42017-09-06 04:38:22 -0700199 static void ThreadMain(void* context);
tommi0b942152017-03-10 09:33:53 -0800200
nisse341c8e42017-09-06 04:38:22 -0700201 class WorkerThread : public PlatformThread {
202 public:
203 WorkerThread(ThreadRunFunction func,
204 void* obj,
205 const char* thread_name,
206 ThreadPriority priority)
207 : PlatformThread(func, obj, thread_name, priority) {}
208
209 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
210 return PlatformThread::QueueAPC(apc_function, data);
211 }
tommi0b942152017-03-10 09:33:53 -0800212 };
213
nisse341c8e42017-09-06 04:38:22 -0700214 class ThreadState {
215 public:
216 explicit ThreadState(HANDLE in_queue) : in_queue_(in_queue) {}
217 ~ThreadState() {}
218
219 void RunThreadMain();
220
221 private:
222 bool ProcessQueuedMessages();
223 void RunDueTasks();
224 void ScheduleNextTimer();
225 void CancelTimers();
226
227 // Since priority_queue<> by defult orders items in terms of
228 // largest->smallest, using std::less<>, and we want smallest->largest,
229 // we would like to use std::greater<> here. Alas it's only available in
230 // C++14 and later, so we roll our own compare template that that relies on
231 // operator<().
232 template <typename T>
233 struct greater {
234 bool operator()(const T& l, const T& r) { return l > r; }
235 };
236
237 MultimediaTimer timer_;
238 std::priority_queue<DelayedTaskInfo,
239 std::vector<DelayedTaskInfo>,
240 greater<DelayedTaskInfo>>
241 timer_tasks_;
242 UINT_PTR timer_id_ = 0;
243 HANDLE in_queue_;
244 };
245
246 TaskQueue* const queue_;
247 WorkerThread thread_;
248 rtc::CriticalSection pending_lock_;
danilchapa37de392017-09-09 04:17:22 -0700249 std::queue<std::unique_ptr<QueuedTask>> pending_
250 RTC_GUARDED_BY(pending_lock_);
tommi83722262017-03-15 04:36:29 -0700251 HANDLE in_queue_;
tommi0b942152017-03-10 09:33:53 -0800252};
253
nisse341c8e42017-09-06 04:38:22 -0700254TaskQueue::Impl::Impl(const char* queue_name,
255 TaskQueue* queue,
256 Priority priority)
257 : queue_(queue),
258 thread_(&TaskQueue::Impl::ThreadMain,
tommic9bb7912017-02-24 10:42:14 -0800259 this,
260 queue_name,
tommi83722262017-03-15 04:36:29 -0700261 TaskQueuePriorityToThreadPriority(priority)),
nisse341c8e42017-09-06 04:38:22 -0700262 in_queue_(::CreateEvent(nullptr, true, false, nullptr)) {
tommic06b1332016-05-14 11:31:40 -0700263 RTC_DCHECK(queue_name);
tommi83722262017-03-15 04:36:29 -0700264 RTC_DCHECK(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700265 thread_.Start();
266 Event event(false, false);
267 ThreadStartupData startup = {&event, this};
268 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread,
269 reinterpret_cast<ULONG_PTR>(&startup)));
270 event.Wait(Event::kForever);
271}
272
nisse341c8e42017-09-06 04:38:22 -0700273TaskQueue::Impl::~Impl() {
tommic06b1332016-05-14 11:31:40 -0700274 RTC_DCHECK(!IsCurrent());
tommif9d91542017-02-17 02:47:11 -0800275 while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) {
kwiberg352444f2016-11-28 15:58:53 -0800276 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError());
tommic06b1332016-05-14 11:31:40 -0700277 Sleep(1);
278 }
279 thread_.Stop();
tommi83722262017-03-15 04:36:29 -0700280 ::CloseHandle(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700281}
282
283// static
nisse341c8e42017-09-06 04:38:22 -0700284TaskQueue::Impl* TaskQueue::Impl::Current() {
285 return static_cast<TaskQueue::Impl*>(::TlsGetValue(GetQueuePtrTls()));
tommic06b1332016-05-14 11:31:40 -0700286}
287
nisse341c8e42017-09-06 04:38:22 -0700288// static
289TaskQueue* TaskQueue::Impl::CurrentQueue() {
290 TaskQueue::Impl* current = Current();
291 return current ? current->queue_ : nullptr;
292}
293
294bool TaskQueue::Impl::IsCurrent() const {
tommic06b1332016-05-14 11:31:40 -0700295 return IsThreadRefEqual(thread_.GetThreadRef(), CurrentThreadRef());
296}
297
nisse341c8e42017-09-06 04:38:22 -0700298void TaskQueue::Impl::PostTask(std::unique_ptr<QueuedTask> task) {
tommi83722262017-03-15 04:36:29 -0700299 rtc::CritScope lock(&pending_lock_);
300 pending_.push(std::move(task));
301 ::SetEvent(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700302}
303
nisse341c8e42017-09-06 04:38:22 -0700304void TaskQueue::Impl::PostDelayedTask(std::unique_ptr<QueuedTask> task,
305 uint32_t milliseconds) {
tommi0b942152017-03-10 09:33:53 -0800306 if (!milliseconds) {
307 PostTask(std::move(task));
308 return;
309 }
310
311 // TODO(tommi): Avoid this allocation. It is currently here since
312 // the timestamp stored in the task info object, is a 64bit timestamp
313 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the
314 // task pointer and timestamp as LPARAM and WPARAM.
315 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task));
316 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0,
317 reinterpret_cast<LPARAM>(task_info))) {
318 delete task_info;
tommic06b1332016-05-14 11:31:40 -0700319 }
320}
321
nisse341c8e42017-09-06 04:38:22 -0700322void TaskQueue::Impl::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
323 std::unique_ptr<QueuedTask> reply,
324 TaskQueue::Impl* reply_queue) {
tommic06b1332016-05-14 11:31:40 -0700325 QueuedTask* task_ptr = task.release();
326 QueuedTask* reply_task_ptr = reply.release();
327 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef();
328 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() {
329 if (task_ptr->Run())
330 delete task_ptr;
331 // If the thread's message queue is full, we can't queue the task and will
332 // have to drop it (i.e. delete).
tommif9d91542017-02-17 02:47:11 -0800333 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0,
334 reinterpret_cast<LPARAM>(reply_task_ptr))) {
tommic06b1332016-05-14 11:31:40 -0700335 delete reply_task_ptr;
336 }
337 });
338}
339
nisse341c8e42017-09-06 04:38:22 -0700340void TaskQueue::Impl::RunPendingTasks() {
tommi83722262017-03-15 04:36:29 -0700341 while (true) {
342 std::unique_ptr<QueuedTask> task;
343 {
344 rtc::CritScope lock(&pending_lock_);
345 if (pending_.empty())
346 break;
347 task = std::move(pending_.front());
348 pending_.pop();
349 }
350
351 if (!task->Run())
352 task.release();
353 }
354}
355
tommic06b1332016-05-14 11:31:40 -0700356// static
nisse341c8e42017-09-06 04:38:22 -0700357void TaskQueue::Impl::ThreadMain(void* context) {
358 ThreadState state(static_cast<TaskQueue::Impl*>(context)->in_queue_);
tommi0b942152017-03-10 09:33:53 -0800359 state.RunThreadMain();
360}
tommif9d91542017-02-17 02:47:11 -0800361
nisse341c8e42017-09-06 04:38:22 -0700362void TaskQueue::Impl::ThreadState::RunThreadMain() {
tommi83722262017-03-15 04:36:29 -0700363 HANDLE handles[2] = { *timer_.event_for_wait(), in_queue_ };
tommib89257a2016-07-12 01:24:36 -0700364 while (true) {
tommif9d91542017-02-17 02:47:11 -0800365 // Make sure we do an alertable wait as that's required to allow APCs to run
366 // (e.g. required for InitializeQueueThread and stopping the thread in
367 // PlatformThread).
tommi0b942152017-03-10 09:33:53 -0800368 DWORD result = ::MsgWaitForMultipleObjectsEx(
tommi83722262017-03-15 04:36:29 -0700369 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE);
tommib89257a2016-07-12 01:24:36 -0700370 RTC_CHECK_NE(WAIT_FAILED, result);
tommi83722262017-03-15 04:36:29 -0700371 if (result == (WAIT_OBJECT_0 + 2)) {
tommi0b942152017-03-10 09:33:53 -0800372 // There are messages in the message queue that need to be handled.
373 if (!ProcessQueuedMessages())
tommib89257a2016-07-12 01:24:36 -0700374 break;
tommi83722262017-03-15 04:36:29 -0700375 }
376
377 if (result == WAIT_OBJECT_0 || (!timer_tasks_.empty() &&
378 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) {
tommi0b942152017-03-10 09:33:53 -0800379 // The multimedia timer was signaled.
380 timer_.Cancel();
tommi0b942152017-03-10 09:33:53 -0800381 RunDueTasks();
382 ScheduleNextTimer();
tommi83722262017-03-15 04:36:29 -0700383 }
384
385 if (result == (WAIT_OBJECT_0 + 1)) {
386 ::ResetEvent(in_queue_);
nisse341c8e42017-09-06 04:38:22 -0700387 TaskQueue::Impl::Current()->RunPendingTasks();
tommib89257a2016-07-12 01:24:36 -0700388 }
389 }
tommib89257a2016-07-12 01:24:36 -0700390}
tommic06b1332016-05-14 11:31:40 -0700391
nisse341c8e42017-09-06 04:38:22 -0700392bool TaskQueue::Impl::ThreadState::ProcessQueuedMessages() {
tommib89257a2016-07-12 01:24:36 -0700393 MSG msg = {};
tommi83722262017-03-15 04:36:29 -0700394 // To protect against overly busy message queues, we limit the time
395 // we process tasks to a few milliseconds. If we don't do that, there's
396 // a chance that timer tasks won't ever run.
397 static const int kMaxTaskProcessingTimeMs = 500;
398 auto start = GetTick();
tommif9d91542017-02-17 02:47:11 -0800399 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) &&
tommib89257a2016-07-12 01:24:36 -0700400 msg.message != WM_QUIT) {
tommic06b1332016-05-14 11:31:40 -0700401 if (!msg.hwnd) {
402 switch (msg.message) {
tommi83722262017-03-15 04:36:29 -0700403 // TODO(tommi): Stop using this way of queueing tasks.
tommic06b1332016-05-14 11:31:40 -0700404 case WM_RUN_TASK: {
405 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam);
406 if (task->Run())
407 delete task;
408 break;
409 }
410 case WM_QUEUE_DELAYED_TASK: {
tommi0b942152017-03-10 09:33:53 -0800411 std::unique_ptr<DelayedTaskInfo> info(
412 reinterpret_cast<DelayedTaskInfo*>(msg.lParam));
413 bool need_to_schedule_timers =
414 timer_tasks_.empty() ||
415 timer_tasks_.top().due_time() > info->due_time();
416 timer_tasks_.emplace(std::move(*info.get()));
417 if (need_to_schedule_timers) {
418 CancelTimers();
419 ScheduleNextTimer();
tommif9d91542017-02-17 02:47:11 -0800420 }
tommic06b1332016-05-14 11:31:40 -0700421 break;
422 }
423 case WM_TIMER: {
tommi0b942152017-03-10 09:33:53 -0800424 RTC_DCHECK_EQ(timer_id_, msg.wParam);
tommif9d91542017-02-17 02:47:11 -0800425 ::KillTimer(nullptr, msg.wParam);
tommi0b942152017-03-10 09:33:53 -0800426 timer_id_ = 0;
427 RunDueTasks();
428 ScheduleNextTimer();
tommic06b1332016-05-14 11:31:40 -0700429 break;
430 }
431 default:
432 RTC_NOTREACHED();
433 break;
434 }
435 } else {
tommif9d91542017-02-17 02:47:11 -0800436 ::TranslateMessage(&msg);
437 ::DispatchMessage(&msg);
tommic06b1332016-05-14 11:31:40 -0700438 }
tommi83722262017-03-15 04:36:29 -0700439
440 if (GetTick() > start + kMaxTaskProcessingTimeMs)
441 break;
tommic06b1332016-05-14 11:31:40 -0700442 }
tommib89257a2016-07-12 01:24:36 -0700443 return msg.message != WM_QUIT;
tommic06b1332016-05-14 11:31:40 -0700444}
tommib89257a2016-07-12 01:24:36 -0700445
nisse341c8e42017-09-06 04:38:22 -0700446void TaskQueue::Impl::ThreadState::RunDueTasks() {
tommi0b942152017-03-10 09:33:53 -0800447 RTC_DCHECK(!timer_tasks_.empty());
448 auto now = GetTick();
449 do {
450 const auto& top = timer_tasks_.top();
451 if (top.due_time() > now)
452 break;
453 top.Run();
454 timer_tasks_.pop();
455 } while (!timer_tasks_.empty());
456}
457
nisse341c8e42017-09-06 04:38:22 -0700458void TaskQueue::Impl::ThreadState::ScheduleNextTimer() {
tommi0b942152017-03-10 09:33:53 -0800459 RTC_DCHECK_EQ(timer_id_, 0);
460 if (timer_tasks_.empty())
461 return;
462
463 const auto& next_task = timer_tasks_.top();
464 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick());
465 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms);
466 if (!timer_.StartOneShotTimer(milliseconds))
467 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr);
468}
469
nisse341c8e42017-09-06 04:38:22 -0700470void TaskQueue::Impl::ThreadState::CancelTimers() {
tommi0b942152017-03-10 09:33:53 -0800471 timer_.Cancel();
472 if (timer_id_) {
473 ::KillTimer(nullptr, timer_id_);
474 timer_id_ = 0;
475 }
476}
477
nisse341c8e42017-09-06 04:38:22 -0700478// Boilerplate for the PIMPL pattern.
479TaskQueue::TaskQueue(const char* queue_name, Priority priority)
480 : impl_(new RefCountedObject<TaskQueue::Impl>(queue_name, this, priority)) {
481}
482
483TaskQueue::~TaskQueue() {}
484
485// static
486TaskQueue* TaskQueue::Current() {
487 return TaskQueue::Impl::CurrentQueue();
488}
489
490// Used for DCHECKing the current queue.
491bool TaskQueue::IsCurrent() const {
492 return impl_->IsCurrent();
493}
494
495void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) {
496 return TaskQueue::impl_->PostTask(std::move(task));
497}
498
499void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
500 std::unique_ptr<QueuedTask> reply,
501 TaskQueue* reply_queue) {
502 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
503 reply_queue->impl_.get());
504}
505
506void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
507 std::unique_ptr<QueuedTask> reply) {
508 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
509 impl_.get());
510}
511
512void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task,
513 uint32_t milliseconds) {
514 return TaskQueue::impl_->PostDelayedTask(std::move(task), milliseconds);
515}
516
tommic06b1332016-05-14 11:31:40 -0700517} // namespace rtc