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

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

Issue 1156503005: 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 indent 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') | no next file » | 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,
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
81 // super-long delay. 82 // super-long delay.
82 return timeout < 0 ? 0 : 83 return timeout < 0 ? 0 :
83 (timeout > std::numeric_limits<int>::max() ? 84 (timeout > std::numeric_limits<int>::max() ?
84 std::numeric_limits<int>::max() : static_cast<int>(timeout)); 85 std::numeric_limits<int>::max() : static_cast<int>(timeout));
85 } 86 }
86 87
87 //----------------------------------------------------------------------------- 88 //-----------------------------------------------------------------------------
88 // MessagePumpForUI public: 89 // MessagePumpForUI public:
89 90
90 MessagePumpForUI::MessagePumpForUI() 91 MessagePumpForUI::MessagePumpForUI()
91 : atom_(0) { 92 : atom_(0),
93 exit_ui_worker_thread_(false) {
92 InitMessageWnd(); 94 InitMessageWnd();
95 ui_worker_thread_.reset(new base::Thread("UI Pump Worker thread"));
cpu_(ooo_6.6-7.5) 2015/05/28 22:45:51 can we do this only when we are nested?
ananta 2015/05/29 00:51:28 We only do this now when we have tasks. Difficult
96 ui_worker_thread_->Start();
97 ui_worker_thread_->task_runner()->PostTask(
98 FROM_HERE,
99 base::Bind(&MessagePumpForUI::DoWorkerThreadRunLoop,
100 base::Unretained(this)));
93 } 101 }
94 102
95 MessagePumpForUI::~MessagePumpForUI() { 103 MessagePumpForUI::~MessagePumpForUI() {
96 DestroyWindow(message_hwnd_); 104 DestroyWindow(message_hwnd_);
97 UnregisterClass(MAKEINTATOM(atom_), 105 UnregisterClass(MAKEINTATOM(atom_),
98 GetModuleFromAddress(&WndProcThunk)); 106 GetModuleFromAddress(&WndProcThunk));
107
108 ::QueueUserAPC(
109 reinterpret_cast<PAPCFUNC>(&MessagePumpForUI::ShutdownWorkerThread),
110 ui_worker_thread_->thread_handle().platform_handle(),
111 reinterpret_cast<ULONG_PTR>(this));
112 ui_worker_thread_->Stop();
99 } 113 }
100 114
101 void MessagePumpForUI::ScheduleWork() { 115 void MessagePumpForUI::ScheduleWork() {
102 if (InterlockedExchange(&have_work_, 1)) 116 return;
103 return; // Someone else continued the pumping.
104
105 // Make sure the MessagePump does some work for us.
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 } 117 }
123 118
124 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { 119 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
125 delayed_work_time_ = delayed_work_time; 120 delayed_work_time_ = delayed_work_time;
126 RescheduleTimer(); 121 RescheduleTimer();
127 } 122 }
128 123
129 //----------------------------------------------------------------------------- 124 //-----------------------------------------------------------------------------
130 // MessagePumpForUI private: 125 // MessagePumpForUI private:
131 126
(...skipping 141 matching lines...) Expand 10 before | Expand all | Expand 10 after
273 return; 268 return;
274 } 269 }
275 270
276 // Let whatever would have run had we not been putting messages in the queue 271 // 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 272 // run now. This is an attempt to make our dummy message not starve other
278 // messages that may be in the Windows message queue. 273 // messages that may be in the Windows message queue.
279 ProcessPumpReplacementMessage(); 274 ProcessPumpReplacementMessage();
280 275
281 // Now give the delegate a chance to do some work. He'll let us know if he 276 // Now give the delegate a chance to do some work. He'll let us know if he
282 // needs to do more work. 277 // needs to do more work.
283 if (state_->delegate->DoWork()) 278 state_->delegate->DoWork();
284 ScheduleWork();
285 state_->delegate->DoDelayedWork(&delayed_work_time_); 279 state_->delegate->DoDelayedWork(&delayed_work_time_);
286 RescheduleTimer(); 280 RescheduleTimer();
287 } 281 }
288 282
289 void MessagePumpForUI::HandleTimerMessage() { 283 void MessagePumpForUI::HandleTimerMessage() {
290 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this)); 284 KillTimer(message_hwnd_, reinterpret_cast<UINT_PTR>(this));
291 285
292 // If we are being called outside of the context of Run, then don't do 286 // 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 287 // anything. This could correspond to a MessageBox call or something of
294 // that sort. 288 // that sort.
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
428 FROM_HERE_WITH_EXPLICIT_FUNCTION( 422 FROM_HERE_WITH_EXPLICIT_FUNCTION(
429 "440919 MessagePumpForUI::ProcessMessageHelper6")); 423 "440919 MessagePumpForUI::ProcessMessageHelper6"));
430 424
431 DispatchMessage(&msg); 425 DispatchMessage(&msg);
432 } 426 }
433 427
434 return true; 428 return true;
435 } 429 }
436 430
437 bool MessagePumpForUI::ProcessPumpReplacementMessage() { 431 bool MessagePumpForUI::ProcessPumpReplacementMessage() {
438 // When we encounter a kMsgHaveWork message, this method is called to peek
439 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The
440 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though
441 // a continuous stream of such messages are posted. This method carefully
442 // peeks a message while there is no chance for a kMsgHaveWork to be pending,
443 // then resets the have_work_ flag (allowing a replacement kMsgHaveWork to
444 // possibly be posted), and finally dispatches that peeked replacement. Note
445 // that the re-post of kMsgHaveWork may be asynchronous to this thread!!
446
447 bool have_message = false;
448 MSG msg;
449 // We should not process all window messages if we are in the context of an
450 // OS modal loop, i.e. in the context of a windows API call like MessageBox.
451 // This is to ensure that these messages are peeked out by the OS modal loop.
452 if (MessageLoop::current()->os_modal_loop()) {
453 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above.
454 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) ||
455 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE);
456 } else {
457 have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE;
458 }
459
460 DCHECK(!have_message || kMsgHaveWork != msg.message ||
461 msg.hwnd != message_hwnd_);
462
463 // Since we discarded a kMsgHaveWork message, we must update the flag. 432 // Since we discarded a kMsgHaveWork message, we must update the flag.
464 int old_have_work = InterlockedExchange(&have_work_, 0); 433 int old_have_work = InterlockedExchange(&have_work_, 0);
465 DCHECK(old_have_work); 434 DCHECK(old_have_work);
435 return true;
436 }
466 437
467 // We don't need a special time slice if we didn't have_message to process. 438 void MessagePumpForUI::DoWorkerThreadRunLoop() {
468 if (!have_message) 439 base::win::ScopedHandle timer(::CreateWaitableTimer(NULL, FALSE, NULL));
469 return false; 440 LARGE_INTEGER due_time = {0};
441 // 3 milliseconds.
442 due_time.QuadPart = -30000;
443 BOOL ret = ::SetWaitableTimer(timer.Get(), &due_time, 3, NULL, NULL, FALSE);
444 CHECK(ret);
470 445
471 // Guarantee we'll get another time slice in the case where we go into native 446 while (!exit_ui_worker_thread_) {
472 // windows code. This ScheduleWork() may hurt performance a tiny bit when 447 DWORD ret = WaitForSingleObjectEx(timer.Get(), INFINITE, TRUE);
473 // tasks appear very infrequently, but when the event queue is busy, the 448 if (ret == WAIT_OBJECT_0) {
cpu_(ooo_6.6-7.5) 2015/05/28 22:45:12 instead of using exit_ui_worker_thread_ rather use
ananta 2015/05/29 00:51:28 Done.
474 // kMsgHaveWork events get (percentage wise) rarer and rarer. 449 if (InterlockedExchange(&have_work_, 1))
475 ScheduleWork(); 450 continue; // Someone else continued the pumping.
476 return ProcessMessageHelper(msg); 451
452 // Make sure the MessagePump does some work for us.
453 BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork,
454 reinterpret_cast<WPARAM>(this),
455 0);
456 if (!ret) {
457 // We have failed to insert a have-work message, so there is a chance
458 // that we will starve tasks/timers while sitting in a nested message
459 // loop. Nested loops only look at Windows Message queues, and don't
460 // look at *our* task queues, etc., so we might not get a time slice in
461 // such. :-(
462 // We could abort here, but the fear is that this failure mode is
463 // plausibly common (queue is full, of about 2000 messages), so we'll
464 // do a near-graceful recovery. Nested loops are pretty transient
465 // (we think), so this will probably be recoverable.
466 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem",
467 MESSAGE_POST_ERROR,
468 MESSAGE_LOOP_PROBLEM_MAX);
469 }
470 }
471 }
472 }
473
474 // static
475 void CALLBACK MessagePumpForUI::ShutdownWorkerThread(ULONG_PTR param) {
476 MessagePumpForUI* instance = reinterpret_cast<MessagePumpForUI*>(param);
477 CHECK(instance);
cpu_(ooo_6.6-7.5) 2015/05/28 22:45:12 you can remove the 477 check
ananta 2015/05/29 00:51:28 Done.
478 instance->exit_ui_worker_thread_ = true;
477 } 479 }
478 480
479 //----------------------------------------------------------------------------- 481 //-----------------------------------------------------------------------------
480 // MessagePumpForIO public: 482 // MessagePumpForIO public:
481 483
482 MessagePumpForIO::MessagePumpForIO() { 484 MessagePumpForIO::MessagePumpForIO() {
483 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1)); 485 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1));
484 DCHECK(port_.IsValid()); 486 DCHECK(port_.IsValid());
485 } 487 }
486 488
(...skipping 211 matching lines...) Expand 10 before | Expand all | Expand 10 after
698 700
699 // static 701 // static
700 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler( 702 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler(
701 ULONG_PTR key, 703 ULONG_PTR key,
702 bool* has_valid_io_context) { 704 bool* has_valid_io_context) {
703 *has_valid_io_context = ((key & 1) == 0); 705 *has_valid_io_context = ((key & 1) == 0);
704 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1)); 706 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1));
705 } 707 }
706 708
707 } // namespace base 709 } // namespace base
OLDNEW
« no previous file with comments | « base/message_loop/message_pump_win.h ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698