Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(691)

Side by Side Diff: base/message_loop/message_pump_win.cc

Issue 1194673004: Don't peek messages in the MessagePumpForUI class when we receive our kMsgHaveWork message. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fix the crash reported in bug 501602. The patch description has been updated with comments about th… Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « base/message_loop/message_pump_win.h ('k') | content/gpu/gpu_main.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/message_loop/message_pump_win.h" 5 #include "base/message_loop/message_pump_win.h"
6 6
7 #include <limits> 7 #include <limits>
8 #include <math.h> 8 #include <math.h>
9 9
10 #include "base/message_loop/message_loop.h" 10 #include "base/message_loop/message_loop.h"
11 #include "base/metrics/histogram.h" 11 #include "base/metrics/histogram.h"
12 #include "base/process/memory.h" 12 #include "base/process/memory.h"
13 #include "base/profiler/scoped_tracker.h" 13 #include "base/profiler/scoped_tracker.h"
14 #include "base/strings/stringprintf.h" 14 #include "base/strings/stringprintf.h"
15 #include "base/threading/thread.h"
15 #include "base/trace_event/trace_event.h" 16 #include "base/trace_event/trace_event.h"
16 #include "base/win/wrapped_window_proc.h" 17 #include "base/win/wrapped_window_proc.h"
17 18
18 namespace base { 19 namespace base {
19 20
20 namespace { 21 namespace {
21 22
22 enum MessageLoopProblems { 23 enum MessageLoopProblems {
23 MESSAGE_POST_ERROR, 24 MESSAGE_POST_ERROR,
24 COMPLETION_POST_ERROR, 25 COMPLETION_POST_ERROR,
25 SET_TIMER_ERROR, 26 SET_TIMER_ERROR,
26 MESSAGE_LOOP_PROBLEM_MAX, 27 MESSAGE_LOOP_PROBLEM_MAX,
27 }; 28 };
28 29
29 } // namespace 30 } // namespace
30 31
31 static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p"; 32 static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p";
32 33
33 // Message sent to get an additional time slice for pumping (processing) another 34 // Message sent to get an additional time slice for pumping (processing) another
34 // task (a series of such messages creates a continuous task pump). 35 // task (a series of such messages creates a continuous task pump).
35 static const int kMsgHaveWork = WM_USER + 1; 36 static const int kMsgHaveWork = WM_USER + 1;
36 37
38 // The default delay for the waitable timer used to wake up the UI worker
39 // thread.
40 static const int64 kDefaultUIWorkerThreadWakeupTimerMs = 3;
41
37 //----------------------------------------------------------------------------- 42 //-----------------------------------------------------------------------------
38 // MessagePumpWin public: 43 // MessagePumpWin public:
39 44
40 void MessagePumpWin::RunWithDispatcher( 45 void MessagePumpWin::RunWithDispatcher(
41 Delegate* delegate, MessagePumpDispatcher* dispatcher) { 46 Delegate* delegate, MessagePumpDispatcher* dispatcher) {
42 RunState s; 47 RunState s;
43 s.delegate = delegate; 48 s.delegate = delegate;
44 s.dispatcher = dispatcher; 49 s.dispatcher = dispatcher;
45 s.should_quit = false; 50 s.should_quit = false;
46 s.run_depth = state_ ? state_->run_depth + 1 : 1; 51 s.run_depth = state_ ? state_->run_depth + 1 : 1;
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
81 // super-long delay. 86 // super-long delay.
82 return timeout < 0 ? 0 : 87 return timeout < 0 ? 0 :
83 (timeout > std::numeric_limits<int>::max() ? 88 (timeout > std::numeric_limits<int>::max() ?
84 std::numeric_limits<int>::max() : static_cast<int>(timeout)); 89 std::numeric_limits<int>::max() : static_cast<int>(timeout));
85 } 90 }
86 91
87 //----------------------------------------------------------------------------- 92 //-----------------------------------------------------------------------------
88 // MessagePumpForUI public: 93 // MessagePumpForUI public:
89 94
90 MessagePumpForUI::MessagePumpForUI() 95 MessagePumpForUI::MessagePumpForUI()
91 : atom_(0) { 96 : atom_(0),
97 force_fallback_timer_for_tasks_(0) {
92 InitMessageWnd(); 98 InitMessageWnd();
99
100 ui_worker_thread_timer_.Set(::CreateWaitableTimer(NULL, FALSE, NULL));
101 ui_worker_thread_.reset(new base::Thread("UI Pump Worker thread"));
102 ui_worker_thread_->Start();
103 ui_worker_thread_->WaitUntilThreadStarted();
104 ui_worker_thread_->task_runner()->PostTask(
105 FROM_HERE,
106 base::Bind(&MessagePumpForUI::DoWorkerThreadRunLoop,
107 base::Unretained(this)));
93 } 108 }
94 109
95 MessagePumpForUI::~MessagePumpForUI() { 110 MessagePumpForUI::~MessagePumpForUI() {
96 DestroyWindow(message_hwnd_); 111 DestroyWindow(message_hwnd_);
97 UnregisterClass(MAKEINTATOM(atom_), 112 UnregisterClass(MAKEINTATOM(atom_),
98 GetModuleFromAddress(&WndProcThunk)); 113 GetModuleFromAddress(&WndProcThunk));
114
115 ::QueueUserAPC(
116 reinterpret_cast<PAPCFUNC>(&MessagePumpForUI::ShutdownWorkerThread),
117 ui_worker_thread_->thread_handle().platform_handle(), NULL);
118 ui_worker_thread_->Stop();
99 } 119 }
100 120
101 void MessagePumpForUI::ScheduleWork() { 121 void MessagePumpForUI::ScheduleWork() {
102 if (InterlockedExchange(&have_work_, 1)) 122 // If we have a regular posted task at the head of queue then we need to
103 return; // Someone else continued the pumping. 123 // process it quickly.
124 if (state_ && state_->delegate->GetNewlyAddedTaskDelay().is_null()) {
125 // Make sure the MessagePump does some work for us.
126 PostWorkMessage();
127 return;
128 }
104 129
105 // Make sure the MessagePump does some work for us. 130 ScheduleWorkHelper();
106 BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork,
107 reinterpret_cast<WPARAM>(this), 0);
108 if (ret)
109 return; // There was room in the Window Message queue.
110
111 // We have failed to insert a have-work message, so there is a chance that we
112 // will starve tasks/timers while sitting in a nested message loop. Nested
113 // loops only look at Windows Message queues, and don't look at *our* task
114 // queues, etc., so we might not get a time slice in such. :-(
115 // We could abort here, but the fear is that this failure mode is plausibly
116 // common (queue is full, of about 2000 messages), so we'll do a near-graceful
117 // recovery. Nested loops are pretty transient (we think), so this will
118 // probably be recoverable.
119 InterlockedExchange(&have_work_, 0); // Clarify that we didn't really insert.
120 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", MESSAGE_POST_ERROR,
121 MESSAGE_LOOP_PROBLEM_MAX);
122 } 131 }
123 132
124 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { 133 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
125 delayed_work_time_ = delayed_work_time; 134 delayed_work_time_ = delayed_work_time;
126 RescheduleTimer(); 135 RescheduleTimer();
127 } 136 }
128 137
129 //----------------------------------------------------------------------------- 138 //-----------------------------------------------------------------------------
130 // MessagePumpForUI private: 139 // MessagePumpForUI private:
131 140
(...skipping 142 matching lines...) Expand 10 before | Expand all | Expand 10 after
274 } 283 }
275 284
276 // Let whatever would have run had we not been putting messages in the queue 285 // Let whatever would have run had we not been putting messages in the queue
277 // run now. This is an attempt to make our dummy message not starve other 286 // run now. This is an attempt to make our dummy message not starve other
278 // messages that may be in the Windows message queue. 287 // messages that may be in the Windows message queue.
279 ProcessPumpReplacementMessage(); 288 ProcessPumpReplacementMessage();
280 289
281 // Now give the delegate a chance to do some work. He'll let us know if he 290 // Now give the delegate a chance to do some work. He'll let us know if he
282 // needs to do more work. 291 // needs to do more work.
283 if (state_->delegate->DoWork()) 292 if (state_->delegate->DoWork())
284 ScheduleWork(); 293 ScheduleWorkHelper();
285 state_->delegate->DoDelayedWork(&delayed_work_time_); 294 state_->delegate->DoDelayedWork(&delayed_work_time_);
286 RescheduleTimer(); 295 RescheduleTimer();
287 } 296 }
288 297
289 void MessagePumpForUI::HandleTimerMessage() { 298 void MessagePumpForUI::HandleTimerMessage() {
290 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this)); 299 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
291 300
292 // If we are being called outside of the context of Run, then don't do 301 // If we are being called outside of the context of Run, then don't do
293 // anything. This could correspond to a MessageBox call or something of 302 // anything. This could correspond to a MessageBox call or something of
294 // that sort. 303 // that sort.
(...skipping 23 matching lines...) Expand all
318 // run loop itself. 327 // run loop itself.
319 // 328 //
320 // We use a single SetTimer corresponding to the timer that will expire 329 // We use a single SetTimer corresponding to the timer that will expire
321 // soonest. As new timers are created and destroyed, we update SetTimer. 330 // soonest. As new timers are created and destroyed, we update SetTimer.
322 // Getting a spurrious SetTimer event firing is benign, as we'll just be 331 // Getting a spurrious SetTimer event firing is benign, as we'll just be
323 // processing an empty timer queue. 332 // processing an empty timer queue.
324 // 333 //
325 int delay_msec = GetCurrentDelay(); 334 int delay_msec = GetCurrentDelay();
326 DCHECK_GE(delay_msec, 0); 335 DCHECK_GE(delay_msec, 0);
327 if (delay_msec == 0) { 336 if (delay_msec == 0) {
328 ScheduleWork(); 337 ScheduleWorkHelper();
329 } else { 338 } else {
330 if (delay_msec < USER_TIMER_MINIMUM) 339 if (delay_msec < USER_TIMER_MINIMUM)
331 delay_msec = USER_TIMER_MINIMUM; 340 delay_msec = USER_TIMER_MINIMUM;
332 341
333 // Create a WM_TIMER event that will wake us up to check for any pending 342 // Create a WM_TIMER event that will wake us up to check for any pending
334 // timers (in case we are running within a nested, external sub-pump). 343 // timers (in case we are running within a nested, external sub-pump).
335 BOOL ret = SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this), 344 BOOL ret = SetTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this),
336 delay_msec, NULL); 345 delay_msec, NULL);
337 if (ret) 346 if (ret)
338 return; 347 return;
(...skipping 63 matching lines...) Expand 10 before | Expand all | Expand 10 after
402 state_->should_quit = true; 411 state_->should_quit = true;
403 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) { 412 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) {
404 TranslateMessage(&msg); 413 TranslateMessage(&msg);
405 DispatchMessage(&msg); 414 DispatchMessage(&msg);
406 } 415 }
407 416
408 return true; 417 return true;
409 } 418 }
410 419
411 bool MessagePumpForUI::ProcessPumpReplacementMessage() { 420 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
412 // When we encounter a kMsgHaveWork message, this method is called to peek 421 // Since we discarded a kMsgHaveWork message, we must update the flag.
413 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The 422 InterlockedExchange(&have_work_, 0);
414 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though 423 return true;
415 // a continuous stream of such messages are posted. This method carefully 424 }
416 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
417 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
418 // possibly be posted), and finally dispatches that peeked replacement. Note
419 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
420 425
421 bool have_message = false; 426 void MessagePumpForUI::DoWorkerThreadRunLoop() {
422 MSG msg; 427 DCHECK(ui_worker_thread_timer_.Get());
423 // We should not process all window messages if we are in the context of an 428 while (TRUE) {
424 // OS modal loop, i.e. in the context of a windows API call like MessageBox. 429 DWORD ret = WaitForSingleObjectEx(
425 // This is to ensure that these messages are peeked out by the OS modal loop. 430 ui_worker_thread_timer_.Get(), INFINITE, TRUE);
426 if (MessageLoop::current()->os_modal_loop()) { 431 // The only APC this thread could receive is the Shutdown APC.
427 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above. 432 if (ret == WAIT_IO_COMPLETION)
428 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) || 433 return;
429 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE); 434
430 } else { 435 // Make sure the MessagePump does some work for us.
431 have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE; 436 PostWorkMessage();
437
438 // Set a one shot timer to process pending delayed tasks if any in the
439 // queue. The actual resolution of the timer is dependent on the current
440 // global timer precision and therefore depends on whether Chrome or any
441 // other process has raised the timer frequency with timeBeginPeriod."
442
443 // We should set the timer only once for each iteration. The
444 // InterlockedExchange call below achieves that.
445 if (::InterlockedExchange(&force_fallback_timer_for_tasks_, 0))
446 SetWakeupTimer(kDefaultUIWorkerThreadWakeupTimerMs);
432 } 447 }
448 }
433 449
434 DCHECK(!have_message || kMsgHaveWork != msg.message || 450 // static
435 msg.hwnd != message_hwnd_); 451 void CALLBACK MessagePumpForUI::ShutdownWorkerThread(ULONG_PTR param) {
452 // This function is empty because we only use the fact that an APC was posted
453 // to the worker thread to shut it down.
454 return;
455 }
436 456
437 // Since we discarded a kMsgHaveWork message, we must update the flag. 457 void MessagePumpForUI::PostWorkMessage() {
438 int old_have_work = InterlockedExchange(&have_work_, 0); 458 BOOL posted = PostMessage(message_hwnd_, kMsgHaveWork,
439 DCHECK(old_have_work); 459 reinterpret_cast<WPARAM>(this),
460 0);
461 if (!posted) {
462 // We have failed to insert a have-work message, so there is a chance
463 // that we will starve tasks/timers while sitting in a nested message
464 // loop. Nested loops only look at Windows Message queues, and don't
465 // look at *our* task queues, etc., so we might not get a time slice in
466 // such. :-(
467 // We could abort here, but the fear is that this failure mode is
468 // plausibly common (queue is full, of about 2000 messages), so we'll
469 // do a near-graceful recovery. Nested loops are pretty transient
470 // (we think), so this will probably be recoverable.
471 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem",
472 MESSAGE_POST_ERROR,
473 MESSAGE_LOOP_PROBLEM_MAX);
474 }
475 }
440 476
441 // We don't need a special time slice if we didn't have_message to process. 477 void MessagePumpForUI::SetWakeupTimer(int64 delay_ms) {
442 if (!have_message) 478 // Set the timer for the delay passed in. The actual resolution of the
443 return false; 479 // timer is dependent on whether timeBeginPeriod was called.
480 LARGE_INTEGER due_time = {0};
dcheng 2015/07/01 22:50:47 FYI, when you reland this, please use {} instead o
481 due_time.QuadPart = -delay_ms * 10000;
482 BOOL timer_set = ::SetWaitableTimer(ui_worker_thread_timer_.Get(),
483 &due_time, 0, NULL, NULL, FALSE);
484 CHECK(timer_set);
485 }
444 486
445 // Guarantee we'll get another time slice in the case where we go into native 487 void MessagePumpForUI::ScheduleWorkHelper() {
446 // windows code. This ScheduleWork() may hurt performance a tiny bit when 488 // Set the flag which allows the UI worker thread to repost the timer to
447 // tasks appear very infrequently, but when the event queue is busy, the 489 // process tasks which may not have been ready to run in the first iteration.
448 // kMsgHaveWork events get (percentage wise) rarer and rarer. 490 ::InterlockedExchange(&force_fallback_timer_for_tasks_, 1);
449 ScheduleWork(); 491
450 return ProcessMessageHelper(msg); 492 // Set a one shot timer to fire after 3 milliseconds. The actual resolution
493 // of the timer is dependent on the current global timer precision and
494 // therefore depends on whether Chrome or any other process has raised the
495 // timer frequency with timeBeginPeriod."
496 SetWakeupTimer(kDefaultUIWorkerThreadWakeupTimerMs);
451 } 497 }
452 498
453 //----------------------------------------------------------------------------- 499 //-----------------------------------------------------------------------------
454 // MessagePumpForIO public: 500 // MessagePumpForIO public:
455 501
456 MessagePumpForIO::MessagePumpForIO() { 502 MessagePumpForIO::MessagePumpForIO() {
457 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1)); 503 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1));
458 DCHECK(port_.IsValid()); 504 DCHECK(port_.IsValid());
459 } 505 }
460 506
(...skipping 211 matching lines...) Expand 10 before | Expand all | Expand 10 after
672 718
673 // static 719 // static
674 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler( 720 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler(
675 ULONG_PTR key, 721 ULONG_PTR key,
676 bool* has_valid_io_context) { 722 bool* has_valid_io_context) {
677 *has_valid_io_context = ((key & 1) == 0); 723 *has_valid_io_context = ((key & 1) == 0);
678 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1)); 724 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1));
679 } 725 }
680 726
681 } // namespace base 727 } // namespace base
OLDNEW
« no previous file with comments | « base/message_loop/message_pump_win.h ('k') | content/gpu/gpu_main.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698