Commit 9d44a9b5 authored by Gabriel Charette's avatar Gabriel Charette Committed by Commit Bot

[base] Migrate Android's MessagePumpForUI to DoSomeWork().

The tricky part is the need to yield to java before declaring
idle. Previously this was done by only yielding to java if we
did any work. With DoSomeWork() however we do not know if we
did any work, we only know whether there's more work to come.
As such we use a special bit to yield to java once and declare
idle if no other work is scheduled in-between now and java
invoking us again.

Bug: 885371
Change-Id: Id9c8271cc216d06a2db7b9a95636fe87b285eb93
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1485130Reviewed-by: default avatarAlex Clarke <alexclarke@chromium.org>
Reviewed-by: default avatarMichael Thiessen <mthiesse@chromium.org>
Commit-Queue: Gabriel Charette <gab@chromium.org>
Auto-Submit: Gabriel Charette <gab@chromium.org>
Cr-Commit-Position: refs/heads/master@{#654883}
parent 6ea313ef
...@@ -59,8 +59,8 @@ class BASE_EXPORT MessagePump { ...@@ -59,8 +59,8 @@ class BASE_EXPORT MessagePump {
// |!delayed_run_time.is_max()|; and it will not be invoked again until // |!delayed_run_time.is_max()|; and it will not be invoked again until
// ScheduleWork() otherwise. Redundant/spurious invocations outside of those // ScheduleWork() otherwise. Redundant/spurious invocations outside of those
// guarantees are not impossible however. DoIdleWork() will not be called so // guarantees are not impossible however. DoIdleWork() will not be called so
// long as this returns a null |delayed_run_time|. See design doc for // long as this returns a NextWorkInfo which is_immediate(). See design doc
// details : // for details :
// https://docs.google.com/document/d/1no1JMli6F1r8gTF9KDIOvoWkUUZcXDktPf4A1IXYc3M/edit# // https://docs.google.com/document/d/1no1JMli6F1r8gTF9KDIOvoWkUUZcXDktPf4A1IXYc3M/edit#
virtual NextWorkInfo DoSomeWork() = 0; virtual NextWorkInfo DoSomeWork() = 0;
...@@ -158,12 +158,16 @@ class BASE_EXPORT MessagePump { ...@@ -158,12 +158,16 @@ class BASE_EXPORT MessagePump {
// only be used on the thread that called Run. // only be used on the thread that called Run.
virtual void Quit() = 0; virtual void Quit() = 0;
// Schedule a DoWork callback to happen reasonably soon. Does nothing if a // Schedule a DoSomeWork callback to happen reasonably soon. Does nothing if
// DoWork callback is already scheduled. Once this call is made, DoWork should // a DoSomeWork callback is already scheduled. Once this call is made,
// not be "starved" at least until it returns a value of false. Thread-safe // DoSomeWork is guaranteed to be called repeatedly at least until it returns
// (and callers should avoid holding a Lock at all cost while making this call // a non-immediate NextWorkInfo (or, if this pump wasn't yet migrated,
// as some platforms' priority boosting features have been observed to cause // DoWork() will be called until it returns false). This call can be expensive
// the caller to get descheduled : https://crbug.com/890978). // and callers should attempt not to invoke it again before a non-immediate
// NextWorkInfo was returned from DoSomeWork(). Thread-safe (and callers
// should avoid holding a Lock at all cost while making this call as some
// platforms' priority boosting features have been observed to cause the
// caller to get descheduled : https://crbug.com/890978).
virtual void ScheduleWork() = 0; virtual void ScheduleWork() = 0;
// Schedule a DoDelayedWork callback to happen at the specified time, // Schedule a DoDelayedWork callback to happen at the specified time,
......
...@@ -121,6 +121,8 @@ MessagePumpForUI::~MessagePumpForUI() { ...@@ -121,6 +121,8 @@ MessagePumpForUI::~MessagePumpForUI() {
} }
void MessagePumpForUI::OnDelayedLooperCallback() { void MessagePumpForUI::OnDelayedLooperCallback() {
// ALooper_pollOnce may call this after Quit() if OnNonDelayedLooperCallback()
// resulted in Quit() in the same round.
if (ShouldQuit()) if (ShouldQuit())
return; return;
...@@ -139,74 +141,98 @@ void MessagePumpForUI::OnDelayedLooperCallback() { ...@@ -139,74 +141,98 @@ void MessagePumpForUI::OnDelayedLooperCallback() {
// there are no obvious timing or multi-threading related issues. // there are no obvious timing or multi-threading related issues.
DPCHECK(ret >= 0 || errno == EAGAIN); DPCHECK(ret >= 0 || errno == EAGAIN);
delayed_scheduled_time_ = base::TimeTicks(); delayed_scheduled_time_.reset();
Delegate::NextWorkInfo next_work_info = delegate_->DoSomeWork();
base::TimeTicks next_delayed_work_time;
delegate_->DoDelayedWork(&next_delayed_work_time);
if (!next_delayed_work_time.is_null()) {
ScheduleDelayedWork(next_delayed_work_time);
}
if (ShouldQuit()) if (ShouldQuit())
return; return;
// We may be idle now, so pump the loop to find out.
ScheduleWork(); if (next_work_info.is_immediate()) {
ScheduleWork();
return;
}
DoIdleWork();
if (!next_work_info.delayed_run_time.is_max())
ScheduleDelayedWork(next_work_info.delayed_run_time);
} }
void MessagePumpForUI::OnNonDelayedLooperCallback() { void MessagePumpForUI::OnNonDelayedLooperCallback() {
base::TimeTicks next_delayed_work_time; // ALooper_pollOnce may call this after Quit() if OnDelayedLooperCallback()
bool did_any_work = false; // resulted in Quit() in the same round.
if (ShouldQuit())
return;
// Runs all native tasks scheduled to run, scheduling delayed work if // A bit added to the |non_delayed_fd_| to keep it signaled when we yield to
// necessary. // java tasks below.
while (true) { constexpr uint64_t kTryJavaTasksBeforeIdleBit = uint64_t(1) << 32;
bool did_work_this_loop = false;
if (ShouldQuit()) // We're about to process all the work requested by ScheduleWork().
return; // MessagePump users are expected to do their best not to invoke
did_work_this_loop = delegate_->DoWork(); // ScheduleWork() again before DoSomeWork() returns a non-immediate
// NextWorkInfo below. Hence, capturing the file descriptor's value now and
// resetting its contents to 0 should be okay. The value currently stored
// should be greater than 0 since work having been scheduled is the reason
// we're here. See http://man7.org/linux/man-pages/man2/eventfd.2.html
uint64_t pre_work_value = 0;
int ret = read(non_delayed_fd_, &pre_work_value, sizeof(pre_work_value));
DPCHECK(ret >= 0);
DCHECK_GT(pre_work_value, 0U);
// Note: We can't skip DoSomeWork() even if
// |pre_work_value == kTryJavaTasksBeforeIdleBit| here (i.e. no additional
// ScheduleWork() since yielding to java) as delayed tasks might have come in
// and we need to re-sample |next_work_info|.
// Runs all application tasks scheduled to run.
Delegate::NextWorkInfo next_work_info;
do {
if (ShouldQuit()) if (ShouldQuit())
return; return;
did_work_this_loop |= delegate_->DoDelayedWork(&next_delayed_work_time); next_work_info = delegate_->DoSomeWork();
} while (next_work_info.is_immediate());
did_any_work |= did_work_this_loop; // Do not resignal |non_delayed_fd_| if we're quitting (this pump doesn't
// allow nesting so needing to resume in an outer loop is not an issue
// either).
if (ShouldQuit())
return;
// If we didn't do any work, we're out of native tasks to run, and we should // Before declaring this loop idle, yield to java tasks and arrange to be
// return control to the looper to run Java tasks. // called again (unless we're already in that second call).
if (!did_work_this_loop) if (pre_work_value != kTryJavaTasksBeforeIdleBit) {
break; // Note: This write() is racing with potential ScheduleWork() calls. This is
} // fine as write() is adding this bit, not overwriting the existing value,
// If we did any work, return control to the looper to run java tasks before // and as such racing ScheduleWork() calls would merely add 1 to the lower
// we call DoIdleWork(). We haven't cleared the fd yet, so we'll get woken up // bits and we would find |pre_work_value != kTryJavaTasksBeforeIdleBit| in
// again soon to check for idle-ness. // the next cycle again, retrying this.
if (did_any_work) ret = write(non_delayed_fd_, &kTryJavaTasksBeforeIdleBit,
sizeof(kTryJavaTasksBeforeIdleBit));
DPCHECK(ret >= 0);
return; return;
}
// We yielded to java tasks already and they didn't generate a ScheduleWork()
// request so we can declare idleness. It's possible for a ScheduleWork()
// request to come in racily while this method unwinds, this is fine and will
// merely result in it being re-invoked shortly after it returns.
DCHECK_EQ(pre_work_value, kTryJavaTasksBeforeIdleBit);
if (ShouldQuit()) if (ShouldQuit())
return; return;
// Read the file descriptor, resetting its contents to 0 and reading back the // At this point, the java looper might not be idle - it's impossible to know
// stored value. // pre-Android-M, so we may end up doing Idle work while java tasks are still
// See http://man7.org/linux/man-pages/man2/eventfd.2.html // queued up. Note that this won't cause us to fail to run java tasks using
uint64_t value = 0; // QuitWhenIdle, as the JavaHandlerThread will finish running all currently
int ret = read(non_delayed_fd_, &value, sizeof(value)); // scheduled tasks before it quits. Also note that we can't just add an idle
DPCHECK(ret >= 0); // callback to the java looper, as that will fire even if application tasks
// are still queued up.
// If we read a value > 1, it means we lost the race to clear the fd before a DoIdleWork();
// new task was posted. This is okay, we can just re-schedule work. if (!next_work_info.delayed_run_time.is_max())
if (value > 1) { ScheduleDelayedWork(next_work_info.delayed_run_time);
ScheduleWork();
} else {
// At this point, the java looper might not be idle - it's impossible to
// know pre-Android-M, so we may end up doing Idle work while java tasks are
// still queued up. Note that this won't cause us to fail to run java tasks
// using QuitWhenIdle, as the JavaHandlerThread will finish running all
// currently scheduled tasks before it quits. Also note that we can't just
// add an idle callback to the java looper, as that will fire even if native
// tasks are still queued up.
DoIdleWork();
if (!next_delayed_work_time.is_null()) {
ScheduleDelayedWork(next_delayed_work_time);
}
}
} }
void MessagePumpForUI::DoIdleWork() { void MessagePumpForUI::DoIdleWork() {
...@@ -296,10 +322,8 @@ void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) { ...@@ -296,10 +322,8 @@ void MessagePumpForUI::ScheduleDelayedWork(const TimeTicks& delayed_work_time) {
if (ShouldQuit()) if (ShouldQuit())
return; return;
if (!delayed_scheduled_time_.is_null() && if (delayed_scheduled_time_ && *delayed_scheduled_time_ == delayed_work_time)
delayed_work_time >= delayed_scheduled_time_) {
return; return;
}
DCHECK(!delayed_work_time.is_null()); DCHECK(!delayed_work_time.is_null());
delayed_scheduled_time_ = delayed_work_time; delayed_scheduled_time_ = delayed_work_time;
......
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
#include "base/compiler_specific.h" #include "base/compiler_specific.h"
#include "base/macros.h" #include "base/macros.h"
#include "base/message_loop/message_pump.h" #include "base/message_loop/message_pump.h"
#include "base/optional.h"
#include "base/time/time.h" #include "base/time/time.h"
struct ALooper; struct ALooper;
...@@ -79,8 +80,10 @@ class BASE_EXPORT MessagePumpForUI : public MessagePump { ...@@ -79,8 +80,10 @@ class BASE_EXPORT MessagePumpForUI : public MessagePump {
Delegate* delegate_ = nullptr; Delegate* delegate_ = nullptr;
// The time at which we are currently scheduled to wake up and perform a // The time at which we are currently scheduled to wake up and perform a
// delayed task. // delayed task. This avoids redundantly scheduling |delayed_fd_| with the
base::TimeTicks delayed_scheduled_time_; // same timeout when subsequent work phases all go idle on the same pending
// delayed task; nullopt if no wakeup is currently scheduled.
Optional<TimeTicks> delayed_scheduled_time_;
// If set, a callback to fire when the message pump is quit. // If set, a callback to fire when the message pump is quit.
base::OnceClosure on_quit_callback_; base::OnceClosure on_quit_callback_;
......
...@@ -44,7 +44,7 @@ bool PumpTypeUsesDoSomeWork(MessageLoop::Type type) { ...@@ -44,7 +44,7 @@ bool PumpTypeUsesDoSomeWork(MessageLoop::Type type) {
// iOS uses a MessagePumpDefault for UI in unit tests, ref. // iOS uses a MessagePumpDefault for UI in unit tests, ref.
// test_support_ios.mm::CreateMessagePumpForUIForTests(). // test_support_ios.mm::CreateMessagePumpForUIForTests().
return true; return true;
#elif defined(OS_WIN) #elif defined(OS_WIN) || defined(OS_ANDROID)
return true; return true;
#elif defined(OS_POSIX) && !defined(OS_NACL_SFI) #elif defined(OS_POSIX) && !defined(OS_NACL_SFI)
// MessagePumpLibevent was migrated (ref. message_pump_for_ui.h and // MessagePumpLibevent was migrated (ref. message_pump_for_ui.h and
......
...@@ -113,13 +113,8 @@ class MessagePumpForUIStub : public base::MessagePumpForUI { ...@@ -113,13 +113,8 @@ class MessagePumpForUIStub : public base::MessagePumpForUI {
break; break;
} }
more_work_is_plausible = g_state->delegate->DoWork(); Delegate::NextWorkInfo next_work_info = g_state->delegate->DoSomeWork();
if (g_state->should_quit) more_work_is_plausible = next_work_info.is_immediate();
break;
base::TimeTicks delayed_work_time;
more_work_is_plausible |=
g_state->delegate->DoDelayedWork(&delayed_work_time);
if (g_state->should_quit) if (g_state->should_quit)
break; break;
...@@ -130,7 +125,7 @@ class MessagePumpForUIStub : public base::MessagePumpForUI { ...@@ -130,7 +125,7 @@ class MessagePumpForUIStub : public base::MessagePumpForUI {
if (g_state->should_quit) if (g_state->should_quit)
break; break;
more_work_is_plausible |= !delayed_work_time.is_null(); more_work_is_plausible |= !next_work_info.delayed_run_time.is_max();
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment