| OLD | NEW |
| (Empty) |
| 1 /* | |
| 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 | |
| 11 #include "webrtc/base/task_queue.h" | |
| 12 | |
| 13 #include <mmsystem.h> | |
| 14 #include <string.h> | |
| 15 | |
| 16 #include <algorithm> | |
| 17 #include <queue> | |
| 18 | |
| 19 #include "webrtc/base/arraysize.h" | |
| 20 #include "webrtc/base/checks.h" | |
| 21 #include "webrtc/base/logging.h" | |
| 22 #include "webrtc/base/safe_conversions.h" | |
| 23 #include "webrtc/base/timeutils.h" | |
| 24 | |
| 25 namespace rtc { | |
| 26 namespace { | |
| 27 #define WM_RUN_TASK WM_USER + 1 | |
| 28 #define WM_QUEUE_DELAYED_TASK WM_USER + 2 | |
| 29 | |
| 30 using Priority = TaskQueue::Priority; | |
| 31 | |
| 32 DWORD g_queue_ptr_tls = 0; | |
| 33 | |
| 34 BOOL CALLBACK InitializeTls(PINIT_ONCE init_once, void* param, void** context) { | |
| 35 g_queue_ptr_tls = TlsAlloc(); | |
| 36 return TRUE; | |
| 37 } | |
| 38 | |
| 39 DWORD GetQueuePtrTls() { | |
| 40 static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT; | |
| 41 ::InitOnceExecuteOnce(&init_once, InitializeTls, nullptr, nullptr); | |
| 42 return g_queue_ptr_tls; | |
| 43 } | |
| 44 | |
| 45 struct ThreadStartupData { | |
| 46 Event* started; | |
| 47 void* thread_context; | |
| 48 }; | |
| 49 | |
| 50 void CALLBACK InitializeQueueThread(ULONG_PTR param) { | |
| 51 MSG msg; | |
| 52 ::PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE); | |
| 53 ThreadStartupData* data = reinterpret_cast<ThreadStartupData*>(param); | |
| 54 ::TlsSetValue(GetQueuePtrTls(), data->thread_context); | |
| 55 data->started->Set(); | |
| 56 } | |
| 57 | |
| 58 ThreadPriority TaskQueuePriorityToThreadPriority(Priority priority) { | |
| 59 switch (priority) { | |
| 60 case Priority::HIGH: | |
| 61 return kRealtimePriority; | |
| 62 case Priority::LOW: | |
| 63 return kLowPriority; | |
| 64 case Priority::NORMAL: | |
| 65 return kNormalPriority; | |
| 66 default: | |
| 67 RTC_NOTREACHED(); | |
| 68 break; | |
| 69 } | |
| 70 return kNormalPriority; | |
| 71 } | |
| 72 | |
| 73 int64_t GetTick() { | |
| 74 static const UINT kPeriod = 1; | |
| 75 bool high_res = (timeBeginPeriod(kPeriod) == TIMERR_NOERROR); | |
| 76 int64_t ret = TimeMillis(); | |
| 77 if (high_res) | |
| 78 timeEndPeriod(kPeriod); | |
| 79 return ret; | |
| 80 } | |
| 81 | |
| 82 class DelayedTaskInfo { | |
| 83 public: | |
| 84 // Default ctor needed to support priority_queue::pop(). | |
| 85 DelayedTaskInfo() {} | |
| 86 DelayedTaskInfo(uint32_t milliseconds, std::unique_ptr<QueuedTask> task) | |
| 87 : due_time_(GetTick() + milliseconds), task_(std::move(task)) {} | |
| 88 DelayedTaskInfo(DelayedTaskInfo&&) = default; | |
| 89 | |
| 90 // Implement for priority_queue. | |
| 91 bool operator>(const DelayedTaskInfo& other) const { | |
| 92 return due_time_ > other.due_time_; | |
| 93 } | |
| 94 | |
| 95 // Required by priority_queue::pop(). | |
| 96 DelayedTaskInfo& operator=(DelayedTaskInfo&& other) = default; | |
| 97 | |
| 98 // See below for why this method is const. | |
| 99 void Run() const { | |
| 100 RTC_DCHECK(due_time_); | |
| 101 task_->Run() ? task_.reset() : static_cast<void>(task_.release()); | |
| 102 } | |
| 103 | |
| 104 int64_t due_time() const { return due_time_; } | |
| 105 | |
| 106 private: | |
| 107 int64_t due_time_ = 0; // Absolute timestamp in milliseconds. | |
| 108 | |
| 109 // |task| needs to be mutable because std::priority_queue::top() returns | |
| 110 // a const reference and a key in an ordered queue must not be changed. | |
| 111 // There are two basic workarounds, one using const_cast, which would also | |
| 112 // make the key (|due_time|), non-const and the other is to make the non-key | |
| 113 // (|task|), mutable. | |
| 114 // Because of this, the |task| variable is made private and can only be | |
| 115 // mutated by calling the |Run()| method. | |
| 116 mutable std::unique_ptr<QueuedTask> task_; | |
| 117 }; | |
| 118 | |
| 119 class MultimediaTimer { | |
| 120 public: | |
| 121 // Note: We create an event that requires manual reset. | |
| 122 MultimediaTimer() : event_(::CreateEvent(nullptr, true, false, nullptr)) {} | |
| 123 | |
| 124 ~MultimediaTimer() { | |
| 125 Cancel(); | |
| 126 ::CloseHandle(event_); | |
| 127 } | |
| 128 | |
| 129 bool StartOneShotTimer(UINT delay_ms) { | |
| 130 RTC_DCHECK_EQ(0, timer_id_); | |
| 131 RTC_DCHECK(event_ != nullptr); | |
| 132 timer_id_ = | |
| 133 ::timeSetEvent(delay_ms, 0, reinterpret_cast<LPTIMECALLBACK>(event_), 0, | |
| 134 TIME_ONESHOT | TIME_CALLBACK_EVENT_SET); | |
| 135 return timer_id_ != 0; | |
| 136 } | |
| 137 | |
| 138 void Cancel() { | |
| 139 ::ResetEvent(event_); | |
| 140 if (timer_id_) { | |
| 141 ::timeKillEvent(timer_id_); | |
| 142 timer_id_ = 0; | |
| 143 } | |
| 144 } | |
| 145 | |
| 146 HANDLE* event_for_wait() { return &event_; } | |
| 147 | |
| 148 private: | |
| 149 HANDLE event_ = nullptr; | |
| 150 MMRESULT timer_id_ = 0; | |
| 151 | |
| 152 RTC_DISALLOW_COPY_AND_ASSIGN(MultimediaTimer); | |
| 153 }; | |
| 154 | |
| 155 } // namespace | |
| 156 | |
| 157 class TaskQueue::ThreadState { | |
| 158 public: | |
| 159 explicit ThreadState(HANDLE in_queue) : in_queue_(in_queue) {} | |
| 160 ~ThreadState() {} | |
| 161 | |
| 162 void RunThreadMain(); | |
| 163 | |
| 164 private: | |
| 165 bool ProcessQueuedMessages(); | |
| 166 void RunDueTasks(); | |
| 167 void ScheduleNextTimer(); | |
| 168 void CancelTimers(); | |
| 169 | |
| 170 // Since priority_queue<> by defult orders items in terms of | |
| 171 // largest->smallest, using std::less<>, and we want smallest->largest, | |
| 172 // we would like to use std::greater<> here. Alas it's only available in | |
| 173 // C++14 and later, so we roll our own compare template that that relies on | |
| 174 // operator<(). | |
| 175 template <typename T> | |
| 176 struct greater { | |
| 177 bool operator()(const T& l, const T& r) { return l > r; } | |
| 178 }; | |
| 179 | |
| 180 MultimediaTimer timer_; | |
| 181 std::priority_queue<DelayedTaskInfo, | |
| 182 std::vector<DelayedTaskInfo>, | |
| 183 greater<DelayedTaskInfo>> | |
| 184 timer_tasks_; | |
| 185 UINT_PTR timer_id_ = 0; | |
| 186 HANDLE in_queue_; | |
| 187 }; | |
| 188 | |
| 189 TaskQueue::TaskQueue(const char* queue_name, Priority priority /*= NORMAL*/) | |
| 190 : thread_(&TaskQueue::ThreadMain, | |
| 191 this, | |
| 192 queue_name, | |
| 193 TaskQueuePriorityToThreadPriority(priority)), | |
| 194 in_queue_(::CreateEvent(nullptr, true, false, nullptr)) { | |
| 195 RTC_DCHECK(queue_name); | |
| 196 RTC_DCHECK(in_queue_); | |
| 197 thread_.Start(); | |
| 198 Event event(false, false); | |
| 199 ThreadStartupData startup = {&event, this}; | |
| 200 RTC_CHECK(thread_.QueueAPC(&InitializeQueueThread, | |
| 201 reinterpret_cast<ULONG_PTR>(&startup))); | |
| 202 event.Wait(Event::kForever); | |
| 203 } | |
| 204 | |
| 205 TaskQueue::~TaskQueue() { | |
| 206 RTC_DCHECK(!IsCurrent()); | |
| 207 while (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUIT, 0, 0)) { | |
| 208 RTC_CHECK_EQ(ERROR_NOT_ENOUGH_QUOTA, ::GetLastError()); | |
| 209 Sleep(1); | |
| 210 } | |
| 211 thread_.Stop(); | |
| 212 ::CloseHandle(in_queue_); | |
| 213 } | |
| 214 | |
| 215 // static | |
| 216 TaskQueue* TaskQueue::Current() { | |
| 217 return static_cast<TaskQueue*>(::TlsGetValue(GetQueuePtrTls())); | |
| 218 } | |
| 219 | |
| 220 // static | |
| 221 bool TaskQueue::IsCurrent(const char* queue_name) { | |
| 222 TaskQueue* current = Current(); | |
| 223 return current && current->thread_.name().compare(queue_name) == 0; | |
| 224 } | |
| 225 | |
| 226 bool TaskQueue::IsCurrent() const { | |
| 227 return IsThreadRefEqual(thread_.GetThreadRef(), CurrentThreadRef()); | |
| 228 } | |
| 229 | |
| 230 void TaskQueue::PostTask(std::unique_ptr<QueuedTask> task) { | |
| 231 rtc::CritScope lock(&pending_lock_); | |
| 232 pending_.push(std::move(task)); | |
| 233 ::SetEvent(in_queue_); | |
| 234 } | |
| 235 | |
| 236 void TaskQueue::PostDelayedTask(std::unique_ptr<QueuedTask> task, | |
| 237 uint32_t milliseconds) { | |
| 238 if (!milliseconds) { | |
| 239 PostTask(std::move(task)); | |
| 240 return; | |
| 241 } | |
| 242 | |
| 243 // TODO(tommi): Avoid this allocation. It is currently here since | |
| 244 // the timestamp stored in the task info object, is a 64bit timestamp | |
| 245 // and WPARAM is 32bits in 32bit builds. Otherwise, we could pass the | |
| 246 // task pointer and timestamp as LPARAM and WPARAM. | |
| 247 auto* task_info = new DelayedTaskInfo(milliseconds, std::move(task)); | |
| 248 if (!::PostThreadMessage(thread_.GetThreadRef(), WM_QUEUE_DELAYED_TASK, 0, | |
| 249 reinterpret_cast<LPARAM>(task_info))) { | |
| 250 delete task_info; | |
| 251 } | |
| 252 } | |
| 253 | |
| 254 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, | |
| 255 std::unique_ptr<QueuedTask> reply, | |
| 256 TaskQueue* reply_queue) { | |
| 257 QueuedTask* task_ptr = task.release(); | |
| 258 QueuedTask* reply_task_ptr = reply.release(); | |
| 259 DWORD reply_thread_id = reply_queue->thread_.GetThreadRef(); | |
| 260 PostTask([task_ptr, reply_task_ptr, reply_thread_id]() { | |
| 261 if (task_ptr->Run()) | |
| 262 delete task_ptr; | |
| 263 // If the thread's message queue is full, we can't queue the task and will | |
| 264 // have to drop it (i.e. delete). | |
| 265 if (!::PostThreadMessage(reply_thread_id, WM_RUN_TASK, 0, | |
| 266 reinterpret_cast<LPARAM>(reply_task_ptr))) { | |
| 267 delete reply_task_ptr; | |
| 268 } | |
| 269 }); | |
| 270 } | |
| 271 | |
| 272 void TaskQueue::PostTaskAndReply(std::unique_ptr<QueuedTask> task, | |
| 273 std::unique_ptr<QueuedTask> reply) { | |
| 274 return PostTaskAndReply(std::move(task), std::move(reply), Current()); | |
| 275 } | |
| 276 | |
| 277 void TaskQueue::RunPendingTasks() { | |
| 278 while (true) { | |
| 279 std::unique_ptr<QueuedTask> task; | |
| 280 { | |
| 281 rtc::CritScope lock(&pending_lock_); | |
| 282 if (pending_.empty()) | |
| 283 break; | |
| 284 task = std::move(pending_.front()); | |
| 285 pending_.pop(); | |
| 286 } | |
| 287 | |
| 288 if (!task->Run()) | |
| 289 task.release(); | |
| 290 } | |
| 291 } | |
| 292 | |
| 293 // static | |
| 294 void TaskQueue::ThreadMain(void* context) { | |
| 295 ThreadState state(static_cast<TaskQueue*>(context)->in_queue_); | |
| 296 state.RunThreadMain(); | |
| 297 } | |
| 298 | |
| 299 void TaskQueue::ThreadState::RunThreadMain() { | |
| 300 HANDLE handles[2] = { *timer_.event_for_wait(), in_queue_ }; | |
| 301 while (true) { | |
| 302 // Make sure we do an alertable wait as that's required to allow APCs to run | |
| 303 // (e.g. required for InitializeQueueThread and stopping the thread in | |
| 304 // PlatformThread). | |
| 305 DWORD result = ::MsgWaitForMultipleObjectsEx( | |
| 306 arraysize(handles), handles, INFINITE, QS_ALLEVENTS, MWMO_ALERTABLE); | |
| 307 RTC_CHECK_NE(WAIT_FAILED, result); | |
| 308 if (result == (WAIT_OBJECT_0 + 2)) { | |
| 309 // There are messages in the message queue that need to be handled. | |
| 310 if (!ProcessQueuedMessages()) | |
| 311 break; | |
| 312 } | |
| 313 | |
| 314 if (result == WAIT_OBJECT_0 || (!timer_tasks_.empty() && | |
| 315 ::WaitForSingleObject(*timer_.event_for_wait(), 0) == WAIT_OBJECT_0)) { | |
| 316 // The multimedia timer was signaled. | |
| 317 timer_.Cancel(); | |
| 318 RunDueTasks(); | |
| 319 ScheduleNextTimer(); | |
| 320 } | |
| 321 | |
| 322 if (result == (WAIT_OBJECT_0 + 1)) { | |
| 323 ::ResetEvent(in_queue_); | |
| 324 TaskQueue::Current()->RunPendingTasks(); | |
| 325 } | |
| 326 } | |
| 327 } | |
| 328 | |
| 329 bool TaskQueue::ThreadState::ProcessQueuedMessages() { | |
| 330 MSG msg = {}; | |
| 331 // To protect against overly busy message queues, we limit the time | |
| 332 // we process tasks to a few milliseconds. If we don't do that, there's | |
| 333 // a chance that timer tasks won't ever run. | |
| 334 static const int kMaxTaskProcessingTimeMs = 500; | |
| 335 auto start = GetTick(); | |
| 336 while (::PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE) && | |
| 337 msg.message != WM_QUIT) { | |
| 338 if (!msg.hwnd) { | |
| 339 switch (msg.message) { | |
| 340 // TODO(tommi): Stop using this way of queueing tasks. | |
| 341 case WM_RUN_TASK: { | |
| 342 QueuedTask* task = reinterpret_cast<QueuedTask*>(msg.lParam); | |
| 343 if (task->Run()) | |
| 344 delete task; | |
| 345 break; | |
| 346 } | |
| 347 case WM_QUEUE_DELAYED_TASK: { | |
| 348 std::unique_ptr<DelayedTaskInfo> info( | |
| 349 reinterpret_cast<DelayedTaskInfo*>(msg.lParam)); | |
| 350 bool need_to_schedule_timers = | |
| 351 timer_tasks_.empty() || | |
| 352 timer_tasks_.top().due_time() > info->due_time(); | |
| 353 timer_tasks_.emplace(std::move(*info.get())); | |
| 354 if (need_to_schedule_timers) { | |
| 355 CancelTimers(); | |
| 356 ScheduleNextTimer(); | |
| 357 } | |
| 358 break; | |
| 359 } | |
| 360 case WM_TIMER: { | |
| 361 RTC_DCHECK_EQ(timer_id_, msg.wParam); | |
| 362 ::KillTimer(nullptr, msg.wParam); | |
| 363 timer_id_ = 0; | |
| 364 RunDueTasks(); | |
| 365 ScheduleNextTimer(); | |
| 366 break; | |
| 367 } | |
| 368 default: | |
| 369 RTC_NOTREACHED(); | |
| 370 break; | |
| 371 } | |
| 372 } else { | |
| 373 ::TranslateMessage(&msg); | |
| 374 ::DispatchMessage(&msg); | |
| 375 } | |
| 376 | |
| 377 if (GetTick() > start + kMaxTaskProcessingTimeMs) | |
| 378 break; | |
| 379 } | |
| 380 return msg.message != WM_QUIT; | |
| 381 } | |
| 382 | |
| 383 void TaskQueue::ThreadState::RunDueTasks() { | |
| 384 RTC_DCHECK(!timer_tasks_.empty()); | |
| 385 auto now = GetTick(); | |
| 386 do { | |
| 387 const auto& top = timer_tasks_.top(); | |
| 388 if (top.due_time() > now) | |
| 389 break; | |
| 390 top.Run(); | |
| 391 timer_tasks_.pop(); | |
| 392 } while (!timer_tasks_.empty()); | |
| 393 } | |
| 394 | |
| 395 void TaskQueue::ThreadState::ScheduleNextTimer() { | |
| 396 RTC_DCHECK_EQ(timer_id_, 0); | |
| 397 if (timer_tasks_.empty()) | |
| 398 return; | |
| 399 | |
| 400 const auto& next_task = timer_tasks_.top(); | |
| 401 int64_t delay_ms = std::max(0ll, next_task.due_time() - GetTick()); | |
| 402 uint32_t milliseconds = rtc::dchecked_cast<uint32_t>(delay_ms); | |
| 403 if (!timer_.StartOneShotTimer(milliseconds)) | |
| 404 timer_id_ = ::SetTimer(nullptr, 0, milliseconds, nullptr); | |
| 405 } | |
| 406 | |
| 407 void TaskQueue::ThreadState::CancelTimers() { | |
| 408 timer_.Cancel(); | |
| 409 if (timer_id_) { | |
| 410 ::KillTimer(nullptr, timer_id_); | |
| 411 timer_id_ = 0; | |
| 412 } | |
| 413 } | |
| 414 | |
| 415 } // namespace rtc | |
| OLD | NEW |