OLD | NEW |
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" | |
16 #include "base/trace_event/trace_event.h" | 15 #include "base/trace_event/trace_event.h" |
17 #include "base/win/wrapped_window_proc.h" | 16 #include "base/win/wrapped_window_proc.h" |
18 | 17 |
19 namespace base { | 18 namespace base { |
20 | 19 |
21 namespace { | 20 namespace { |
22 | 21 |
23 enum MessageLoopProblems { | 22 enum MessageLoopProblems { |
24 MESSAGE_POST_ERROR, | 23 MESSAGE_POST_ERROR, |
25 COMPLETION_POST_ERROR, | 24 COMPLETION_POST_ERROR, |
26 SET_TIMER_ERROR, | 25 SET_TIMER_ERROR, |
27 MESSAGE_LOOP_PROBLEM_MAX, | 26 MESSAGE_LOOP_PROBLEM_MAX, |
28 }; | 27 }; |
29 | 28 |
30 } // namespace | 29 } // namespace |
31 | 30 |
32 static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p"; | 31 static const wchar_t kWndClassFormat[] = L"Chrome_MessagePumpWindow_%p"; |
33 | 32 |
34 // Message sent to get an additional time slice for pumping (processing) another | 33 // Message sent to get an additional time slice for pumping (processing) another |
35 // task (a series of such messages creates a continuous task pump). | 34 // task (a series of such messages creates a continuous task pump). |
36 static const int kMsgHaveWork = WM_USER + 1; | 35 static const int kMsgHaveWork = WM_USER + 1; |
37 | 36 |
38 // The default delay for the waitable timer used to wake up the UI worker | |
39 // thread. | |
40 static const int64 kDefaultUIWorkerThreadWakeupTimerMs = 3; | |
41 | |
42 //----------------------------------------------------------------------------- | 37 //----------------------------------------------------------------------------- |
43 // MessagePumpWin public: | 38 // MessagePumpWin public: |
44 | 39 |
45 void MessagePumpWin::RunWithDispatcher( | 40 void MessagePumpWin::RunWithDispatcher( |
46 Delegate* delegate, MessagePumpDispatcher* dispatcher) { | 41 Delegate* delegate, MessagePumpDispatcher* dispatcher) { |
47 RunState s; | 42 RunState s; |
48 s.delegate = delegate; | 43 s.delegate = delegate; |
49 s.dispatcher = dispatcher; | 44 s.dispatcher = dispatcher; |
50 s.should_quit = false; | 45 s.should_quit = false; |
51 s.run_depth = state_ ? state_->run_depth + 1 : 1; | 46 s.run_depth = state_ ? state_->run_depth + 1 : 1; |
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
88 (timeout > std::numeric_limits<int>::max() ? | 83 (timeout > std::numeric_limits<int>::max() ? |
89 std::numeric_limits<int>::max() : static_cast<int>(timeout)); | 84 std::numeric_limits<int>::max() : static_cast<int>(timeout)); |
90 } | 85 } |
91 | 86 |
92 //----------------------------------------------------------------------------- | 87 //----------------------------------------------------------------------------- |
93 // MessagePumpForUI public: | 88 // MessagePumpForUI public: |
94 | 89 |
95 MessagePumpForUI::MessagePumpForUI() | 90 MessagePumpForUI::MessagePumpForUI() |
96 : atom_(0) { | 91 : atom_(0) { |
97 InitMessageWnd(); | 92 InitMessageWnd(); |
98 | |
99 ui_worker_thread_timer_.Set(::CreateWaitableTimer(NULL, FALSE, NULL)); | |
100 ui_worker_thread_.reset(new base::Thread("UI Pump Worker thread")); | |
101 ui_worker_thread_->Start(); | |
102 ui_worker_thread_->task_runner()->PostTask( | |
103 FROM_HERE, | |
104 base::Bind(&MessagePumpForUI::DoWorkerThreadRunLoop, | |
105 base::Unretained(this))); | |
106 } | 93 } |
107 | 94 |
108 MessagePumpForUI::~MessagePumpForUI() { | 95 MessagePumpForUI::~MessagePumpForUI() { |
109 DestroyWindow(message_hwnd_); | 96 DestroyWindow(message_hwnd_); |
110 UnregisterClass(MAKEINTATOM(atom_), | 97 UnregisterClass(MAKEINTATOM(atom_), |
111 GetModuleFromAddress(&WndProcThunk)); | 98 GetModuleFromAddress(&WndProcThunk)); |
112 | |
113 ::QueueUserAPC( | |
114 reinterpret_cast<PAPCFUNC>(&MessagePumpForUI::ShutdownWorkerThread), | |
115 ui_worker_thread_->thread_handle().platform_handle(), NULL); | |
116 ui_worker_thread_->Stop(); | |
117 } | 99 } |
118 | 100 |
119 void MessagePumpForUI::ScheduleWork() { | 101 void MessagePumpForUI::ScheduleWork() { |
120 // If we have a regular posted task at the head of queue then we need to | 102 if (InterlockedExchange(&have_work_, 1)) |
121 // process it quickly. | 103 return; // Someone else continued the pumping. |
122 if (state_ && state_->delegate->GetNewlyAddedTaskDelay().is_null()) { | 104 |
123 // Make sure the MessagePump does some work for us. | 105 // Make sure the MessagePump does some work for us. |
124 PostWorkMessage(); | 106 BOOL ret = PostMessage(message_hwnd_, kMsgHaveWork, |
125 return; | 107 reinterpret_cast<WPARAM>(this), 0); |
126 } | 108 if (ret) |
127 // Set a one shot timer to fire after 3 milliseconds. The actual resolution | 109 return; // There was room in the Window Message queue. |
128 // of the timer is dependent on timeBeginPeriod being called. | 110 |
129 SetWakeupTimer(kDefaultUIWorkerThreadWakeupTimerMs); | 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); |
130 } | 122 } |
131 | 123 |
132 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { | 124 void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { |
133 delayed_work_time_ = delayed_work_time; | 125 delayed_work_time_ = delayed_work_time; |
134 RescheduleTimer(); | 126 RescheduleTimer(); |
135 } | 127 } |
136 | 128 |
137 //----------------------------------------------------------------------------- | 129 //----------------------------------------------------------------------------- |
138 // MessagePumpForUI private: | 130 // MessagePumpForUI private: |
139 | 131 |
(...skipping 270 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
410 state_->should_quit = true; | 402 state_->should_quit = true; |
411 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) { | 403 if (action & MessagePumpDispatcher::POST_DISPATCH_PERFORM_DEFAULT) { |
412 TranslateMessage(&msg); | 404 TranslateMessage(&msg); |
413 DispatchMessage(&msg); | 405 DispatchMessage(&msg); |
414 } | 406 } |
415 | 407 |
416 return true; | 408 return true; |
417 } | 409 } |
418 | 410 |
419 bool MessagePumpForUI::ProcessPumpReplacementMessage() { | 411 bool MessagePumpForUI::ProcessPumpReplacementMessage() { |
| 412 // When we encounter a kMsgHaveWork message, this method is called to peek |
| 413 // and process a replacement message, such as a WM_PAINT or WM_TIMER. The |
| 414 // goal is to make the kMsgHaveWork as non-intrusive as possible, even though |
| 415 // a continuous stream of such messages are posted. This method carefully |
| 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 |
| 421 bool have_message = false; |
| 422 MSG msg; |
| 423 // We should not process all window messages if we are in the context of an |
| 424 // OS modal loop, i.e. in the context of a windows API call like MessageBox. |
| 425 // This is to ensure that these messages are peeked out by the OS modal loop. |
| 426 if (MessageLoop::current()->os_modal_loop()) { |
| 427 // We only peek out WM_PAINT and WM_TIMER here for reasons mentioned above. |
| 428 have_message = PeekMessage(&msg, NULL, WM_PAINT, WM_PAINT, PM_REMOVE) || |
| 429 PeekMessage(&msg, NULL, WM_TIMER, WM_TIMER, PM_REMOVE); |
| 430 } else { |
| 431 have_message = PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) != FALSE; |
| 432 } |
| 433 |
| 434 DCHECK(!have_message || kMsgHaveWork != msg.message || |
| 435 msg.hwnd != message_hwnd_); |
| 436 |
420 // Since we discarded a kMsgHaveWork message, we must update the flag. | 437 // Since we discarded a kMsgHaveWork message, we must update the flag. |
421 InterlockedExchange(&have_work_, 0); | 438 int old_have_work = InterlockedExchange(&have_work_, 0); |
422 return true; | 439 DCHECK(old_have_work); |
423 } | |
424 | 440 |
425 void MessagePumpForUI::DoWorkerThreadRunLoop() { | 441 // We don't need a special time slice if we didn't have_message to process. |
426 DCHECK(ui_worker_thread_timer_.Get()); | 442 if (!have_message) |
427 while (TRUE) { | 443 return false; |
428 DWORD ret = WaitForSingleObjectEx( | |
429 ui_worker_thread_timer_.Get(), INFINITE, TRUE); | |
430 // The only APC this thread could receive is the Shutdown APC. | |
431 if (ret == WAIT_IO_COMPLETION) | |
432 return; | |
433 | 444 |
434 // Make sure the MessagePump does some work for us. | 445 // Guarantee we'll get another time slice in the case where we go into native |
435 PostWorkMessage(); | 446 // windows code. This ScheduleWork() may hurt performance a tiny bit when |
436 | 447 // tasks appear very infrequently, but when the event queue is busy, the |
437 // Set a one shot timer to process pending delayed tasks if any in the | 448 // kMsgHaveWork events get (percentage wise) rarer and rarer. |
438 // queue. The actual resolution of the timer is dependent on the | 449 ScheduleWork(); |
439 // timeBeginPeriod API being called. | 450 return ProcessMessageHelper(msg); |
440 SetWakeupTimer(kDefaultUIWorkerThreadWakeupTimerMs); | |
441 } | |
442 } | |
443 | |
444 // static | |
445 void CALLBACK MessagePumpForUI::ShutdownWorkerThread(ULONG_PTR param) { | |
446 // This function is empty because we only use the fact that an APC was posted | |
447 // to the worker thread to shut it down. | |
448 return; | |
449 } | |
450 | |
451 void MessagePumpForUI::PostWorkMessage() { | |
452 BOOL posted = PostMessage(message_hwnd_, kMsgHaveWork, | |
453 reinterpret_cast<WPARAM>(this), | |
454 0); | |
455 if (!posted) { | |
456 // We have failed to insert a have-work message, so there is a chance | |
457 // that we will starve tasks/timers while sitting in a nested message | |
458 // loop. Nested loops only look at Windows Message queues, and don't | |
459 // look at *our* task queues, etc., so we might not get a time slice in | |
460 // such. :-( | |
461 // We could abort here, but the fear is that this failure mode is | |
462 // plausibly common (queue is full, of about 2000 messages), so we'll | |
463 // do a near-graceful recovery. Nested loops are pretty transient | |
464 // (we think), so this will probably be recoverable. | |
465 UMA_HISTOGRAM_ENUMERATION("Chrome.MessageLoopProblem", | |
466 MESSAGE_POST_ERROR, | |
467 MESSAGE_LOOP_PROBLEM_MAX); | |
468 } | |
469 } | |
470 | |
471 void MessagePumpForUI::SetWakeupTimer(int64 delay_ms) { | |
472 // Set the timer for the delay passed in. The actual resolution of the | |
473 // timer is dependent on whether timeBeginPeriod was called. | |
474 LARGE_INTEGER due_time = {0}; | |
475 due_time.QuadPart = -delay_ms * 10000; | |
476 BOOL timer_set = ::SetWaitableTimer(ui_worker_thread_timer_.Get(), | |
477 &due_time, 0, NULL, NULL, FALSE); | |
478 CHECK(timer_set); | |
479 } | 451 } |
480 | 452 |
481 //----------------------------------------------------------------------------- | 453 //----------------------------------------------------------------------------- |
482 // MessagePumpForIO public: | 454 // MessagePumpForIO public: |
483 | 455 |
484 MessagePumpForIO::MessagePumpForIO() { | 456 MessagePumpForIO::MessagePumpForIO() { |
485 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1)); | 457 port_.Set(CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 1)); |
486 DCHECK(port_.IsValid()); | 458 DCHECK(port_.IsValid()); |
487 } | 459 } |
488 | 460 |
(...skipping 211 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
700 | 672 |
701 // static | 673 // static |
702 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler( | 674 MessagePumpForIO::IOHandler* MessagePumpForIO::KeyToHandler( |
703 ULONG_PTR key, | 675 ULONG_PTR key, |
704 bool* has_valid_io_context) { | 676 bool* has_valid_io_context) { |
705 *has_valid_io_context = ((key & 1) == 0); | 677 *has_valid_io_context = ((key & 1) == 0); |
706 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1)); | 678 return reinterpret_cast<IOHandler*>(key & ~static_cast<ULONG_PTR>(1)); |
707 } | 679 } |
708 | 680 |
709 } // namespace base | 681 } // namespace base |
OLD | NEW |