blob: 5cc9f88d423b4873b7af1b368ad2a20a919f8a09 [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
Niels Möllerb06b0a62018-05-25 10:05:34 +020014// win32.h. To include win32.h directly, it must be broken out into its own
15// build target.
Danil Chapovalov02fddf62018-02-12 12:41:16 +010016#include <winsock2.h>
17#include <windows.h>
18#include <sal.h> // Must come after windows headers.
19#include <mmsystem.h> // Must come after windows headers.
tommic06b1332016-05-14 11:31:40 -070020#include <string.h>
tommic06b1332016-05-14 11:31:40 -070021
tommif9d91542017-02-17 02:47:11 -080022#include <algorithm>
tommi0b942152017-03-10 09:33:53 -080023#include <queue>
Danil Chapovalov6f09ae22017-10-12 14:39:25 +020024#include <utility>
tommif9d91542017-02-17 02:47:11 -080025
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/arraysize.h"
27#include "rtc_base/checks.h"
Danil Chapovalov02fddf62018-02-12 12:41:16 +010028#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/event.h"
30#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010031#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/platform_thread.h"
33#include "rtc_base/refcount.h"
34#include "rtc_base/refcountedobject.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "rtc_base/timeutils.h"
tommic06b1332016-05-14 11:31:40 -070036
37namespace rtc {
38namespace {
39#define WM_RUN_TASK WM_USER + 1
40#define WM_QUEUE_DELAYED_TASK WM_USER + 2
41
tommic9bb7912017-02-24 10:42:14 -080042using Priority = TaskQueue::Priority;
43
tommic06b1332016-05-14 11:31:40 -070044DWORD g_queue_ptr_tls = 0;
45
46BOOL CALLBACK InitializeTls(PINIT_ONCE init_once, void* param, void** context) {
47 g_queue_ptr_tls = TlsAlloc();
48 return TRUE;
49}
50
51DWORD GetQueuePtrTls() {
52 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT;
tommif9d91542017-02-17 02:47:11 -080053 ::InitOnceExecuteOnce(&init_once, InitializeTls, nullptr, nullptr);
tommic06b1332016-05-14 11:31:40 -070054 return g_queue_ptr_tls;
55}
56
57struct ThreadStartupData {
58 Event* started;
59 void* thread_context;
60};
61
62void CALLBACK InitializeQueueThread(ULONG_PTR param) {
63 MSG msg;
tommif9d91542017-02-17 02:47:11 -080064 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
tommic06b1332016-05-14 11:31:40 -070065 ThreadStartupData* data = reinterpret_cast<ThreadStartupData*>(param);
tommif9d91542017-02-17 02:47:11 -080066 ::TlsSetValue(GetQueuePtrTls(), data->thread_context);
tommic06b1332016-05-14 11:31:40 -070067 data->started->Set();
68}
tommic9bb7912017-02-24 10:42:14 -080069
70ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) {
71 switch (priority) {
72 case Priority::HIGH:
73 return kRealtimePriority;
74 case Priority::LOW:
75 return kLowPriority;
76 case Priority::NORMAL:
77 return kNormalPriority;
78 default:
79 RTC_NOTREACHED();
80 break;
81 }
82 return kNormalPriority;
83}
tommi5bdee472017-03-03 05:20:12 -080084
tommi0b942152017-03-10 09:33:53 -080085int64_t GetTick() {
tommi5bdee472017-03-03 05:20:12 -080086 static const UINT kPeriod = 1;
87 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR);
tommi0b942152017-03-10 09:33:53 -080088 int64_t ret = TimeMillis();
tommi5bdee472017-03-03 05:20:12 -080089 if (high_res)
90 timeEndPeriod(kPeriod);
91 return ret;
92}
tommic06b1332016-05-14 11:31:40 -070093
tommi0b942152017-03-10 09:33:53 -080094class DelayedTaskInfo {
tommif9d91542017-02-17 02:47:11 -080095 public:
tommi0b942152017-03-10 09:33:53 -080096 // Default ctor needed to support priority_queue::pop().
97 DelayedTaskInfo() {}
98 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task)
99 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {}
100 DelayedTaskInfo(DelayedTaskInfo&&) = default;
tommif9d91542017-02-17 02:47:11 -0800101
tommi0b942152017-03-10 09:33:53 -0800102 // Implement for priority_queue.
103 bool operator>(const DelayedTaskInfo& other) const {
104 return due_time_ > other.due_time_;
105 }
tommif9d91542017-02-17 02:47:11 -0800106
tommi0b942152017-03-10 09:33:53 -0800107 // Required by priority_queue::pop().
108 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default;
109
110 // See below for why this method is const.
111 void Run() const {
112 RTC_DCHECK(due_time_);
113 task_->Run() ? task_.reset() : static_cast<void>(task_.release());
114 }
115
116 int64_t due_time() const { return due_time_; }
117
118 private:
119 int64_t due_time_ = 0; // Absolute timestamp in milliseconds.
120
121 // |task| needs to be mutable because std::priority_queue::top() returns
122 // a const reference and a key in an ordered queue must not be changed.
123 // There are two basic workarounds, one using const_cast, which would also
124 // make the key (|due_time|), non-const and the other is to make the non-key
125 // (|task|), mutable.
126 // Because of this, the |task| variable is made private and can only be
127 // mutated by calling the |Run()| method.
128 mutable std::unique_ptr<QueuedTask> task_;
129};
130
131class MultimediaTimer {
132 public:
tommi83722262017-03-15 04:36:29 -0700133 // Note: We create an event that requires manual reset.
134 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {}
tommif9d91542017-02-17 02:47:11 -0800135
tommi0b942152017-03-10 09:33:53 -0800136 ~MultimediaTimer() {
137 Cancel();
138 ::CloseHandle(event_);
tommif9d91542017-02-17 02:47:11 -0800139 }
140
tommi0b942152017-03-10 09:33:53 -0800141 bool StartOneShotTimer(UINT delay_ms) {
tommif9d91542017-02-17 02:47:11 -0800142 RTC_DCHECK_EQ(0, timer_id_);
143 RTC_DCHECK(event_ != nullptr);
tommif9d91542017-02-17 02:47:11 -0800144 timer_id_ =
145 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0,
146 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET);
147 return timer_id_ != 0;
148 }
149
tommi0b942152017-03-10 09:33:53 -0800150 void Cancel() {
tommi83722262017-03-15 04:36:29 -0700151 ::ResetEvent(event_);
tommif9d91542017-02-17 02:47:11 -0800152 if (timer_id_) {
153 ::timeKillEvent(timer_id_);
154 timer_id_ = 0;
155 }
tommif9d91542017-02-17 02:47:11 -0800156 }
157
tommi0b942152017-03-10 09:33:53 -0800158 HANDLE* event_for_wait() { return &event_; }
tommif9d91542017-02-17 02:47:11 -0800159
160 private:
tommif9d91542017-02-17 02:47:11 -0800161 HANDLE event_ = nullptr;
162 MMRESULT timer_id_ = 0;
tommif9d91542017-02-17 02:47:11 -0800163
164 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer);
165};
166
tommi0b942152017-03-10 09:33:53 -0800167} // namespace
168
nisse341c8e42017-09-06 04:38:22 -0700169class TaskQueue::Impl : public RefCountInterface {
tommi0b942152017-03-10 09:33:53 -0800170 public:
nisse341c8e42017-09-06 04:38:22 -0700171 Impl(const char* queue_name, TaskQueue* queue, Priority priority);
172 ~Impl() override;
tommi0b942152017-03-10 09:33:53 -0800173
nisse341c8e42017-09-06 04:38:22 -0700174 static TaskQueue::Impl* Current();
175 static TaskQueue* CurrentQueue();
176
177 // Used for DCHECKing the current queue.
178 bool IsCurrent() const;
179
180 template <class Closure,
Danil Chapovalov6f09ae22017-10-12 14:39:25 +0200181 typename std::enable_if<!std::is_convertible<
182 Closure,
183 std::unique_ptr<QueuedTask>>::value>::type* = nullptr>
184 void PostTask(Closure&& closure) {
185 PostTask(NewClosure(std::forward<Closure>(closure)));
nisse341c8e42017-09-06 04:38:22 -0700186 }
187
188 void PostTask(std::unique_ptr<QueuedTask> task);
189 void PostTaskAndReply(std::unique_ptr<QueuedTask> task,
190 std::unique_ptr<QueuedTask> reply,
191 TaskQueue::Impl* reply_queue);
192
193 void PostDelayedTask(std::unique_ptr<QueuedTask> task, uint32_t milliseconds);
194
195 void RunPendingTasks();
tommi0b942152017-03-10 09:33:53 -0800196
197 private:
nisse341c8e42017-09-06 04:38:22 -0700198 static void ThreadMain(void* context);
tommi0b942152017-03-10 09:33:53 -0800199
nisse341c8e42017-09-06 04:38:22 -0700200 class WorkerThread : public PlatformThread {
201 public:
202 WorkerThread(ThreadRunFunction func,
203 void* obj,
204 const char* thread_name,
205 ThreadPriority priority)
206 : PlatformThread(func, obj, thread_name, priority) {}
207
208 bool QueueAPC(PAPCFUNC apc_function, ULONG_PTR data) {
209 return PlatformThread::QueueAPC(apc_function, data);
210 }
tommi0b942152017-03-10 09:33:53 -0800211 };
212
nisse341c8e42017-09-06 04:38:22 -0700213 class ThreadState {
214 public:
215 explicit ThreadState(HANDLE in_queue) : in_queue_(in_queue) {}
216 ~ThreadState() {}
217
218 void RunThreadMain();
219
220 private:
221 bool ProcessQueuedMessages();
222 void RunDueTasks();
223 void ScheduleNextTimer();
224 void CancelTimers();
225
226 // Since priority_queue<> by defult orders items in terms of
227 // largest->smallest, using std::less<>, and we want smallest->largest,
228 // we would like to use std::greater<> here. Alas it's only available in
229 // C++14 and later, so we roll our own compare template that that relies on
230 // operator<().
231 template <typename T>
232 struct greater {
233 bool operator()(const T& l, const T& r) { return l > r; }
234 };
235
236 MultimediaTimer timer_;
237 std::priority_queue<DelayedTaskInfo,
238 std::vector<DelayedTaskInfo>,
239 greater<DelayedTaskInfo>>
240 timer_tasks_;
241 UINT_PTR timer_id_ = 0;
242 HANDLE in_queue_;
243 };
244
245 TaskQueue* const queue_;
246 WorkerThread thread_;
247 rtc::CriticalSection pending_lock_;
danilchapa37de392017-09-09 04:17:22 -0700248 std::queue<std::unique_ptr<QueuedTask>> pending_
249 RTC_GUARDED_BY(pending_lock_);
tommi83722262017-03-15 04:36:29 -0700250 HANDLE in_queue_;
tommi0b942152017-03-10 09:33:53 -0800251};
252
nisse341c8e42017-09-06 04:38:22 -0700253TaskQueue::Impl::Impl(const char* queue_name,
254 TaskQueue* queue,
255 Priority priority)
256 : queue_(queue),
257 thread_(&TaskQueue::Impl::ThreadMain,
tommic9bb7912017-02-24 10:42:14 -0800258 this,
259 queue_name,
tommi83722262017-03-15 04:36:29 -0700260 TaskQueuePriorityToThreadPriority(priority)),
nisse341c8e42017-09-06 04:38:22 -0700261 in_queue_(::CreateEvent(nullptr, true, false, nullptr)) {
tommic06b1332016-05-14 11:31:40 -0700262 RTC_DCHECK(queue_name);
tommi83722262017-03-15 04:36:29 -0700263 RTC_DCHECK(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700264 thread_.Start();
265 Event event(false, false);
266 ThreadStartupData startup = {&event, this};
267 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread,
268 reinterpret_cast<ULONG_PTR>(&startup)));
269 event.Wait(Event::kForever);
270}
271
nisse341c8e42017-09-06 04:38:22 -0700272TaskQueue::Impl::~Impl() {
tommic06b1332016-05-14 11:31:40 -0700273 RTC_DCHECK(!IsCurrent());
tommif9d91542017-02-17 02:47:11 -0800274 while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) {
kwiberg352444f2016-11-28 15:58:53 -0800275 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError());
tommic06b1332016-05-14 11:31:40 -0700276 Sleep(1);
277 }
278 thread_.Stop();
tommi83722262017-03-15 04:36:29 -0700279 ::CloseHandle(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700280}
281
282// static
nisse341c8e42017-09-06 04:38:22 -0700283TaskQueue::Impl* TaskQueue::Impl::Current() {
284 return static_cast<TaskQueue::Impl*>(::TlsGetValue(GetQueuePtrTls()));
tommic06b1332016-05-14 11:31:40 -0700285}
286
nisse341c8e42017-09-06 04:38:22 -0700287// static
288TaskQueue* TaskQueue::Impl::CurrentQueue() {
289 TaskQueue::Impl* current = Current();
290 return current ? current->queue_ : nullptr;
291}
292
293bool TaskQueue::Impl::IsCurrent() const {
tommic06b1332016-05-14 11:31:40 -0700294 return IsThreadRefEqual(thread_.GetThreadRef(), CurrentThreadRef());
295}
296
nisse341c8e42017-09-06 04:38:22 -0700297void TaskQueue::Impl::PostTask(std::unique_ptr<QueuedTask> task) {
tommi83722262017-03-15 04:36:29 -0700298 rtc::CritScope lock(&pending_lock_);
299 pending_.push(std::move(task));
300 ::SetEvent(in_queue_);
tommic06b1332016-05-14 11:31:40 -0700301}
302
nisse341c8e42017-09-06 04:38:22 -0700303void TaskQueue::Impl::PostDelayedTask(std::unique_ptr<QueuedTask> task,
304 uint32_t milliseconds) {
tommi0b942152017-03-10 09:33:53 -0800305 if (!milliseconds) {
306 PostTask(std::move(task));
307 return;
308 }
309
310 // TODO(tommi): Avoid this allocation. It is currently here since
311 // the timestamp stored in the task info object, is a 64bit timestamp
312 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the
313 // task pointer and timestamp as LPARAM and WPARAM.
314 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task));
315 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0,
316 reinterpret_cast<LPARAM>(task_info))) {
317 delete task_info;
tommic06b1332016-05-14 11:31:40 -0700318 }
319}
320
nisse341c8e42017-09-06 04:38:22 -0700321void TaskQueue::Impl::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
322 std::unique_ptr<QueuedTask> reply,
323 TaskQueue::Impl* reply_queue) {
tommic06b1332016-05-14 11:31:40 -0700324 QueuedTask* task_ptr = task.release();
325 QueuedTask* reply_task_ptr = reply.release();
326 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef();
327 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() {
328 if (task_ptr->Run())
329 delete task_ptr;
330 // If the thread's message queue is full, we can't queue the task and will
331 // have to drop it (i.e. delete).
tommif9d91542017-02-17 02:47:11 -0800332 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0,
333 reinterpret_cast<LPARAM>(reply_task_ptr))) {
tommic06b1332016-05-14 11:31:40 -0700334 delete reply_task_ptr;
335 }
336 });
337}
338
nisse341c8e42017-09-06 04:38:22 -0700339void TaskQueue::Impl::RunPendingTasks() {
tommi83722262017-03-15 04:36:29 -0700340 while (true) {
341 std::unique_ptr<QueuedTask> task;
342 {
343 rtc::CritScope lock(&pending_lock_);
344 if (pending_.empty())
345 break;
346 task = std::move(pending_.front());
347 pending_.pop();
348 }
349
350 if (!task->Run())
351 task.release();
352 }
353}
354
tommic06b1332016-05-14 11:31:40 -0700355// static
nisse341c8e42017-09-06 04:38:22 -0700356void TaskQueue::Impl::ThreadMain(void* context) {
357 ThreadState state(static_cast<TaskQueue::Impl*>(context)->in_queue_);
tommi0b942152017-03-10 09:33:53 -0800358 state.RunThreadMain();
359}
tommif9d91542017-02-17 02:47:11 -0800360
nisse341c8e42017-09-06 04:38:22 -0700361void TaskQueue::Impl::ThreadState::RunThreadMain() {
tommi83722262017-03-15 04:36:29 -0700362 HANDLE handles[2] = { *timer_.event_for_wait(), in_queue_ };
tommib89257a2016-07-12 01:24:36 -0700363 while (true) {
tommif9d91542017-02-17 02:47:11 -0800364 // Make sure we do an alertable wait as that's required to allow APCs to run
365 // (e.g. required for InitializeQueueThread and stopping the thread in
366 // PlatformThread).
tommi0b942152017-03-10 09:33:53 -0800367 DWORD result = ::MsgWaitForMultipleObjectsEx(
tommi83722262017-03-15 04:36:29 -0700368 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE);
tommib89257a2016-07-12 01:24:36 -0700369 RTC_CHECK_NE(WAIT_FAILED, result);
tommi83722262017-03-15 04:36:29 -0700370 if (result == (WAIT_OBJECT_0 + 2)) {
tommi0b942152017-03-10 09:33:53 -0800371 // There are messages in the message queue that need to be handled.
372 if (!ProcessQueuedMessages())
tommib89257a2016-07-12 01:24:36 -0700373 break;
tommi83722262017-03-15 04:36:29 -0700374 }
375
376 if (result == WAIT_OBJECT_0 || (!timer_tasks_.empty() &&
377 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) {
tommi0b942152017-03-10 09:33:53 -0800378 // The multimedia timer was signaled.
379 timer_.Cancel();
tommi0b942152017-03-10 09:33:53 -0800380 RunDueTasks();
381 ScheduleNextTimer();
tommi83722262017-03-15 04:36:29 -0700382 }
383
384 if (result == (WAIT_OBJECT_0 + 1)) {
385 ::ResetEvent(in_queue_);
nisse341c8e42017-09-06 04:38:22 -0700386 TaskQueue::Impl::Current()->RunPendingTasks();
tommib89257a2016-07-12 01:24:36 -0700387 }
388 }
tommib89257a2016-07-12 01:24:36 -0700389}
tommic06b1332016-05-14 11:31:40 -0700390
nisse341c8e42017-09-06 04:38:22 -0700391bool TaskQueue::Impl::ThreadState::ProcessQueuedMessages() {
tommib89257a2016-07-12 01:24:36 -0700392 MSG msg = {};
tommi83722262017-03-15 04:36:29 -0700393 // To protect against overly busy message queues, we limit the time
394 // we process tasks to a few milliseconds. If we don't do that, there's
395 // a chance that timer tasks won't ever run.
396 static const int kMaxTaskProcessingTimeMs = 500;
397 auto start = GetTick();
tommif9d91542017-02-17 02:47:11 -0800398 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) &&
tommib89257a2016-07-12 01:24:36 -0700399 msg.message != WM_QUIT) {
tommic06b1332016-05-14 11:31:40 -0700400 if (!msg.hwnd) {
401 switch (msg.message) {
tommi83722262017-03-15 04:36:29 -0700402 // TODO(tommi): Stop using this way of queueing tasks.
tommic06b1332016-05-14 11:31:40 -0700403 case WM_RUN_TASK: {
404 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam);
405 if (task->Run())
406 delete task;
407 break;
408 }
409 case WM_QUEUE_DELAYED_TASK: {
tommi0b942152017-03-10 09:33:53 -0800410 std::unique_ptr<DelayedTaskInfo> info(
411 reinterpret_cast<DelayedTaskInfo*>(msg.lParam));
412 bool need_to_schedule_timers =
413 timer_tasks_.empty() ||
414 timer_tasks_.top().due_time() > info->due_time();
415 timer_tasks_.emplace(std::move(*info.get()));
416 if (need_to_schedule_timers) {
417 CancelTimers();
418 ScheduleNextTimer();
tommif9d91542017-02-17 02:47:11 -0800419 }
tommic06b1332016-05-14 11:31:40 -0700420 break;
421 }
422 case WM_TIMER: {
tommi0b942152017-03-10 09:33:53 -0800423 RTC_DCHECK_EQ(timer_id_, msg.wParam);
tommif9d91542017-02-17 02:47:11 -0800424 ::KillTimer(nullptr, msg.wParam);
tommi0b942152017-03-10 09:33:53 -0800425 timer_id_ = 0;
426 RunDueTasks();
427 ScheduleNextTimer();
tommic06b1332016-05-14 11:31:40 -0700428 break;
429 }
430 default:
431 RTC_NOTREACHED();
432 break;
433 }
434 } else {
tommif9d91542017-02-17 02:47:11 -0800435 ::TranslateMessage(&msg);
436 ::DispatchMessage(&msg);
tommic06b1332016-05-14 11:31:40 -0700437 }
tommi83722262017-03-15 04:36:29 -0700438
439 if (GetTick() > start + kMaxTaskProcessingTimeMs)
440 break;
tommic06b1332016-05-14 11:31:40 -0700441 }
tommib89257a2016-07-12 01:24:36 -0700442 return msg.message != WM_QUIT;
tommic06b1332016-05-14 11:31:40 -0700443}
tommib89257a2016-07-12 01:24:36 -0700444
nisse341c8e42017-09-06 04:38:22 -0700445void TaskQueue::Impl::ThreadState::RunDueTasks() {
tommi0b942152017-03-10 09:33:53 -0800446 RTC_DCHECK(!timer_tasks_.empty());
447 auto now = GetTick();
448 do {
449 const auto& top = timer_tasks_.top();
450 if (top.due_time() > now)
451 break;
452 top.Run();
453 timer_tasks_.pop();
454 } while (!timer_tasks_.empty());
455}
456
nisse341c8e42017-09-06 04:38:22 -0700457void TaskQueue::Impl::ThreadState::ScheduleNextTimer() {
tommi0b942152017-03-10 09:33:53 -0800458 RTC_DCHECK_EQ(timer_id_, 0);
459 if (timer_tasks_.empty())
460 return;
461
462 const auto& next_task = timer_tasks_.top();
463 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick());
464 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms);
465 if (!timer_.StartOneShotTimer(milliseconds))
466 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr);
467}
468
nisse341c8e42017-09-06 04:38:22 -0700469void TaskQueue::Impl::ThreadState::CancelTimers() {
tommi0b942152017-03-10 09:33:53 -0800470 timer_.Cancel();
471 if (timer_id_) {
472 ::KillTimer(nullptr, timer_id_);
473 timer_id_ = 0;
474 }
475}
476
nisse341c8e42017-09-06 04:38:22 -0700477// Boilerplate for the PIMPL pattern.
478TaskQueue::TaskQueue(const char* queue_name, Priority priority)
479 : impl_(new RefCountedObject<TaskQueue::Impl>(queue_name, this, priority)) {
480}
481
482TaskQueue::~TaskQueue() {}
483
484// static
485TaskQueue* TaskQueue::Current() {
486 return TaskQueue::Impl::CurrentQueue();
487}
488
489// Used for DCHECKing the current queue.
490bool TaskQueue::IsCurrent() const {
491 return impl_->IsCurrent();
492}
493
494void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) {
495 return TaskQueue::impl_->PostTask(std::move(task));
496}
497
498void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
499 std::unique_ptr<QueuedTask> reply,
500 TaskQueue* reply_queue) {
501 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
502 reply_queue->impl_.get());
503}
504
505void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task,
506 std::unique_ptr<QueuedTask> reply) {
507 return TaskQueue::impl_->PostTaskAndReply(std::move(task), std::move(reply),
508 impl_.get());
509}
510
511void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task,
512 uint32_t milliseconds) {
513 return TaskQueue::impl_->PostDelayedTask(std::move(task), milliseconds);
514}
515
tommic06b1332016-05-14 11:31:40 -0700516} // namespace rtc