This source file includes following definitions.
- AlwaysNotifyPump
- run_loop_
- run_loop_
- current
- EnableHistogrammer
- InitMessagePumpForUIFactory
- CreateMessagePumpForType
- AddDestructionObserver
- RemoveDestructionObserver
- PostTask
- PostDelayedTask
- PostNonNestableTask
- PostNonNestableDelayedTask
- Run
- RunUntilIdle
- QuitWhenIdle
- QuitNow
- IsType
- QuitCurrentWhenIdle
- QuitWhenIdleClosure
- SetNestableTasksAllowed
- NestableTasksAllowed
- IsNested
- AddTaskObserver
- RemoveTaskObserver
- is_running
- IsHighResolutionTimerEnabledForTesting
- IsIdleForTesting
- Init
- RunHandler
- ProcessNextDelayedNonNestableTask
- RunTask
- DeferOrRunPendingTask
- AddToDelayedWorkQueue
- DeletePendingTasks
- GetTaskTraceID
- ReloadWorkQueue
- ScheduleWork
- StartHistogrammer
- HistogramEvent
- DoWork
- DoDelayedWork
- DoIdleWork
- GetQueueingInformation
- DeleteSoonInternal
- ReleaseSoonInternal
- Start
- Attach
- AddObserver
- RemoveObserver
- RegisterIOHandler
- RegisterJobObject
- WaitForIOCompletion
- WatchFileDescriptor
- WatchFileDescriptor
#include "base/message_loop/message_loop.h"
#include <algorithm>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/debug/alias.h"
#include "base/debug/trace_event.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_pump_default.h"
#include "base/metrics/histogram.h"
#include "base/metrics/statistics_recorder.h"
#include "base/run_loop.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/thread_local.h"
#include "base/time/time.h"
#include "base/tracked_objects.h"
#if defined(OS_MACOSX)
#include "base/message_loop/message_pump_mac.h"
#endif
#if defined(OS_POSIX) && !defined(OS_IOS)
#include "base/message_loop/message_pump_libevent.h"
#endif
#if defined(OS_ANDROID)
#include "base/message_loop/message_pump_android.h"
#endif
#if defined(TOOLKIT_GTK)
#include <gdk/gdk.h>
#include <gdk/gdkx.h>
#endif
namespace base {
namespace {
LazyInstance<base::ThreadLocalPointer<MessageLoop> >::Leaky lazy_tls_ptr =
LAZY_INSTANCE_INITIALIZER;
const int kTaskRunEvent = 0x1;
#if !defined(OS_NACL)
const int kTimerEvent = 0x2;
const int kLeastNonZeroMessageId = 1;
const int kMaxMessageId = 1099;
const int kNumberOfDistinctMessagesDisplayed = 1100;
#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},
const LinearHistogram::DescriptionPair event_descriptions_[] = {
VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
VALUE_TO_NUMBER_AND_NAME(kTimerEvent)
{-1, NULL}
};
#endif
bool enable_histogrammer_ = false;
MessageLoop::MessagePumpFactory* message_pump_for_ui_factory_ = NULL;
bool AlwaysNotifyPump(MessageLoop::Type type) {
#if defined(OS_ANDROID)
return type == MessageLoop::TYPE_UI || type == MessageLoop::TYPE_JAVA;
#else
return false;
#endif
}
}
MessageLoop::TaskObserver::TaskObserver() {
}
MessageLoop::TaskObserver::~TaskObserver() {
}
MessageLoop::DestructionObserver::~DestructionObserver() {
}
MessageLoop::MessageLoop(Type type)
: type_(type),
nestable_tasks_allowed_(true),
#if defined(OS_WIN)
os_modal_loop_(false),
#endif
message_histogram_(NULL),
run_loop_(NULL) {
Init();
pump_ = CreateMessagePumpForType(type).Pass();
}
MessageLoop::MessageLoop(scoped_ptr<MessagePump> pump)
: pump_(pump.Pass()),
type_(TYPE_CUSTOM),
nestable_tasks_allowed_(true),
#if defined(OS_WIN)
os_modal_loop_(false),
#endif
message_histogram_(NULL),
run_loop_(NULL) {
DCHECK(pump_.get());
Init();
}
MessageLoop::~MessageLoop() {
DCHECK_EQ(this, current());
DCHECK(!run_loop_);
bool did_work;
for (int i = 0; i < 100; ++i) {
DeletePendingTasks();
ReloadWorkQueue();
did_work = DeletePendingTasks();
if (!did_work)
break;
}
DCHECK(!did_work);
FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
WillDestroyCurrentMessageLoop());
thread_task_runner_handle_.reset();
incoming_task_queue_->WillDestroyCurrentMessageLoop();
incoming_task_queue_ = NULL;
message_loop_proxy_ = NULL;
lazy_tls_ptr.Pointer()->Set(NULL);
}
MessageLoop* MessageLoop::current() {
return lazy_tls_ptr.Pointer()->Get();
}
void MessageLoop::EnableHistogrammer(bool enable) {
enable_histogrammer_ = enable;
}
bool MessageLoop::InitMessagePumpForUIFactory(MessagePumpFactory* factory) {
if (message_pump_for_ui_factory_)
return false;
message_pump_for_ui_factory_ = factory;
return true;
}
scoped_ptr<MessagePump> MessageLoop::CreateMessagePumpForType(Type type) {
#if defined(OS_WIN)
#define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(new MessagePumpForUI())
#define MESSAGE_PUMP_IO scoped_ptr<MessagePump>(new MessagePumpForIO())
#elif defined(OS_IOS)
#define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(MessagePumpMac::Create())
#define MESSAGE_PUMP_IO scoped_ptr<MessagePump>(new MessagePumpIOSForIO())
#elif defined(OS_MACOSX)
#define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(MessagePumpMac::Create())
#define MESSAGE_PUMP_IO scoped_ptr<MessagePump>(new MessagePumpLibevent())
#elif defined(OS_NACL)
#define MESSAGE_PUMP_UI scoped_ptr<MessagePump>()
#define MESSAGE_PUMP_IO scoped_ptr<MessagePump>(new MessagePumpDefault())
#elif defined(OS_POSIX)
#define MESSAGE_PUMP_UI scoped_ptr<MessagePump>(new MessagePumpForUI())
#define MESSAGE_PUMP_IO scoped_ptr<MessagePump>(new MessagePumpLibevent())
#else
#error Not implemented
#endif
if (type == MessageLoop::TYPE_UI) {
if (message_pump_for_ui_factory_)
return message_pump_for_ui_factory_();
return MESSAGE_PUMP_UI;
}
if (type == MessageLoop::TYPE_IO)
return MESSAGE_PUMP_IO;
#if defined(TOOLKIT_GTK)
if (type == MessageLoop::TYPE_GPU)
return scoped_ptr<MessagePump>(new MessagePumpX11());
#endif
#if defined(OS_ANDROID)
if (type == MessageLoop::TYPE_JAVA)
return MESSAGE_PUMP_UI;
#endif
DCHECK_EQ(MessageLoop::TYPE_DEFAULT, type);
return scoped_ptr<MessagePump>(new MessagePumpDefault());
}
void MessageLoop::AddDestructionObserver(
DestructionObserver* destruction_observer) {
DCHECK_EQ(this, current());
destruction_observers_.AddObserver(destruction_observer);
}
void MessageLoop::RemoveDestructionObserver(
DestructionObserver* destruction_observer) {
DCHECK_EQ(this, current());
destruction_observers_.RemoveObserver(destruction_observer);
}
void MessageLoop::PostTask(
const tracked_objects::Location& from_here,
const Closure& task) {
DCHECK(!task.is_null()) << from_here.ToString();
incoming_task_queue_->AddToIncomingQueue(from_here, task, TimeDelta(), true);
}
void MessageLoop::PostDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
DCHECK(!task.is_null()) << from_here.ToString();
incoming_task_queue_->AddToIncomingQueue(from_here, task, delay, true);
}
void MessageLoop::PostNonNestableTask(
const tracked_objects::Location& from_here,
const Closure& task) {
DCHECK(!task.is_null()) << from_here.ToString();
incoming_task_queue_->AddToIncomingQueue(from_here, task, TimeDelta(), false);
}
void MessageLoop::PostNonNestableDelayedTask(
const tracked_objects::Location& from_here,
const Closure& task,
TimeDelta delay) {
DCHECK(!task.is_null()) << from_here.ToString();
incoming_task_queue_->AddToIncomingQueue(from_here, task, delay, false);
}
void MessageLoop::Run() {
RunLoop run_loop;
run_loop.Run();
}
void MessageLoop::RunUntilIdle() {
RunLoop run_loop;
run_loop.RunUntilIdle();
}
void MessageLoop::QuitWhenIdle() {
DCHECK_EQ(this, current());
if (run_loop_) {
run_loop_->quit_when_idle_received_ = true;
} else {
NOTREACHED() << "Must be inside Run to call Quit";
}
}
void MessageLoop::QuitNow() {
DCHECK_EQ(this, current());
if (run_loop_) {
pump_->Quit();
} else {
NOTREACHED() << "Must be inside Run to call Quit";
}
}
bool MessageLoop::IsType(Type type) const {
return type_ == type;
}
static void QuitCurrentWhenIdle() {
MessageLoop::current()->QuitWhenIdle();
}
Closure MessageLoop::QuitWhenIdleClosure() {
return Bind(&QuitCurrentWhenIdle);
}
void MessageLoop::SetNestableTasksAllowed(bool allowed) {
if (allowed) {
pump_->ScheduleWork();
}
nestable_tasks_allowed_ = allowed;
}
bool MessageLoop::NestableTasksAllowed() const {
return nestable_tasks_allowed_;
}
bool MessageLoop::IsNested() {
return run_loop_->run_depth_ > 1;
}
void MessageLoop::AddTaskObserver(TaskObserver* task_observer) {
DCHECK_EQ(this, current());
task_observers_.AddObserver(task_observer);
}
void MessageLoop::RemoveTaskObserver(TaskObserver* task_observer) {
DCHECK_EQ(this, current());
task_observers_.RemoveObserver(task_observer);
}
bool MessageLoop::is_running() const {
DCHECK_EQ(this, current());
return run_loop_ != NULL;
}
bool MessageLoop::IsHighResolutionTimerEnabledForTesting() {
return incoming_task_queue_->IsHighResolutionTimerEnabledForTesting();
}
bool MessageLoop::IsIdleForTesting() {
return incoming_task_queue_->IsIdleForTesting();
}
void MessageLoop::Init() {
DCHECK(!current()) << "should only have one message loop per thread";
lazy_tls_ptr.Pointer()->Set(this);
incoming_task_queue_ = new internal::IncomingTaskQueue(this);
message_loop_proxy_ =
new internal::MessageLoopProxyImpl(incoming_task_queue_);
thread_task_runner_handle_.reset(
new ThreadTaskRunnerHandle(message_loop_proxy_));
}
void MessageLoop::RunHandler() {
DCHECK_EQ(this, current());
StartHistogrammer();
#if defined(USE_AURA)
if (run_loop_->dispatcher_ && type() == TYPE_UI) {
static_cast<MessagePumpForUI*>(pump_.get())->
RunWithDispatcher(this, run_loop_->dispatcher_);
return;
}
#endif
pump_->Run(this);
}
bool MessageLoop::ProcessNextDelayedNonNestableTask() {
if (run_loop_->run_depth_ != 1)
return false;
if (deferred_non_nestable_work_queue_.empty())
return false;
PendingTask pending_task = deferred_non_nestable_work_queue_.front();
deferred_non_nestable_work_queue_.pop();
RunTask(pending_task);
return true;
}
void MessageLoop::RunTask(const PendingTask& pending_task) {
tracked_objects::TrackedTime start_time =
tracked_objects::ThreadData::NowForStartOfRun(pending_task.birth_tally);
TRACE_EVENT_FLOW_END1(TRACE_DISABLED_BY_DEFAULT("toplevel.flow"),
"MessageLoop::PostTask", TRACE_ID_MANGLE(GetTaskTraceID(pending_task)),
"queue_duration",
(start_time - pending_task.EffectiveTimePosted()).InMilliseconds());
TRACE_EVENT_WITH_MEMORY_TAG2(
"toplevel", "MessageLoop::RunTask",
pending_task.posted_from.function_name(),
"src_file", pending_task.posted_from.file_name(),
"src_func", pending_task.posted_from.function_name());
DCHECK(nestable_tasks_allowed_);
nestable_tasks_allowed_ = false;
const void* program_counter =
pending_task.posted_from.program_counter();
debug::Alias(&program_counter);
HistogramEvent(kTaskRunEvent);
FOR_EACH_OBSERVER(TaskObserver, task_observers_,
WillProcessTask(pending_task));
pending_task.task.Run();
FOR_EACH_OBSERVER(TaskObserver, task_observers_,
DidProcessTask(pending_task));
tracked_objects::ThreadData::TallyRunOnNamedThreadIfTracking(pending_task,
start_time, tracked_objects::ThreadData::NowForEndOfRun());
nestable_tasks_allowed_ = true;
}
bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
if (pending_task.nestable || run_loop_->run_depth_ == 1) {
RunTask(pending_task);
return true;
}
deferred_non_nestable_work_queue_.push(pending_task);
return false;
}
void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
delayed_work_queue_.push(pending_task);
}
bool MessageLoop::DeletePendingTasks() {
bool did_work = !work_queue_.empty();
while (!work_queue_.empty()) {
PendingTask pending_task = work_queue_.front();
work_queue_.pop();
if (!pending_task.delayed_run_time.is_null()) {
AddToDelayedWorkQueue(pending_task);
}
}
did_work |= !deferred_non_nestable_work_queue_.empty();
while (!deferred_non_nestable_work_queue_.empty()) {
deferred_non_nestable_work_queue_.pop();
}
did_work |= !delayed_work_queue_.empty();
while (!delayed_work_queue_.empty()) {
delayed_work_queue_.pop();
}
return did_work;
}
uint64 MessageLoop::GetTaskTraceID(const PendingTask& task) {
return (static_cast<uint64>(task.sequence_num) << 32) |
((static_cast<uint64>(reinterpret_cast<intptr_t>(this)) << 32) >> 32);
}
void MessageLoop::ReloadWorkQueue() {
if (work_queue_.empty())
incoming_task_queue_->ReloadWorkQueue(&work_queue_);
}
void MessageLoop::ScheduleWork(bool was_empty) {
if (was_empty || AlwaysNotifyPump(type_))
pump_->ScheduleWork();
}
void MessageLoop::StartHistogrammer() {
#if !defined(OS_NACL)
if (enable_histogrammer_ && !message_histogram_
&& StatisticsRecorder::IsActive()) {
DCHECK(!thread_name_.empty());
message_histogram_ = LinearHistogram::FactoryGetWithRangeDescription(
"MsgLoop:" + thread_name_,
kLeastNonZeroMessageId, kMaxMessageId,
kNumberOfDistinctMessagesDisplayed,
message_histogram_->kHexRangePrintingFlag,
event_descriptions_);
}
#endif
}
void MessageLoop::HistogramEvent(int event) {
#if !defined(OS_NACL)
if (message_histogram_)
message_histogram_->Add(event);
#endif
}
bool MessageLoop::DoWork() {
if (!nestable_tasks_allowed_) {
return false;
}
for (;;) {
ReloadWorkQueue();
if (work_queue_.empty())
break;
do {
PendingTask pending_task = work_queue_.front();
work_queue_.pop();
if (!pending_task.delayed_run_time.is_null()) {
AddToDelayedWorkQueue(pending_task);
if (delayed_work_queue_.top().task.Equals(pending_task.task))
pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
} else {
if (DeferOrRunPendingTask(pending_task))
return true;
}
} while (!work_queue_.empty());
}
return false;
}
bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) {
if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
recent_time_ = *next_delayed_work_time = TimeTicks();
return false;
}
TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time;
if (next_run_time > recent_time_) {
recent_time_ = TimeTicks::Now();
if (next_run_time > recent_time_) {
*next_delayed_work_time = next_run_time;
return false;
}
}
PendingTask pending_task = delayed_work_queue_.top();
delayed_work_queue_.pop();
if (!delayed_work_queue_.empty())
*next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
return DeferOrRunPendingTask(pending_task);
}
bool MessageLoop::DoIdleWork() {
if (ProcessNextDelayedNonNestableTask())
return true;
if (run_loop_->quit_when_idle_received_)
pump_->Quit();
return false;
}
void MessageLoop::GetQueueingInformation(size_t* queue_size,
TimeDelta* queueing_delay) {
*queue_size = work_queue_.size();
if (*queue_size == 0) {
*queueing_delay = TimeDelta();
return;
}
const PendingTask& next_to_run = work_queue_.front();
tracked_objects::Duration duration =
tracked_objects::TrackedTime::Now() - next_to_run.EffectiveTimePosted();
*queueing_delay = TimeDelta::FromMilliseconds(duration.InMilliseconds());
}
void MessageLoop::DeleteSoonInternal(const tracked_objects::Location& from_here,
void(*deleter)(const void*),
const void* object) {
PostNonNestableTask(from_here, Bind(deleter, object));
}
void MessageLoop::ReleaseSoonInternal(
const tracked_objects::Location& from_here,
void(*releaser)(const void*),
const void* object) {
PostNonNestableTask(from_here, Bind(releaser, object));
}
#if defined(OS_ANDROID)
void MessageLoopForUI::Start() {
static_cast<MessagePumpForUI*>(pump_.get())->Start(this);
}
#endif
#if defined(OS_IOS)
void MessageLoopForUI::Attach() {
static_cast<MessagePumpUIApplication*>(pump_.get())->Attach(this);
}
#endif
#if !defined(OS_NACL) && (defined(TOOLKIT_GTK) || defined(USE_OZONE) || \
defined(OS_WIN) || defined(USE_X11))
void MessageLoopForUI::AddObserver(Observer* observer) {
pump_ui()->AddObserver(observer);
}
void MessageLoopForUI::RemoveObserver(Observer* observer) {
pump_ui()->RemoveObserver(observer);
}
#endif
#if defined(OS_WIN)
void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
pump_io()->RegisterIOHandler(file, handler);
}
bool MessageLoopForIO::RegisterJobObject(HANDLE job, IOHandler* handler) {
return pump_io()->RegisterJobObject(job, handler);
}
bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
return pump_io()->WaitForIOCompletion(timeout, filter);
}
#elif defined(OS_IOS)
bool MessageLoopForIO::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
return pump_io()->WatchFileDescriptor(
fd,
persistent,
mode,
controller,
delegate);
}
#elif defined(OS_POSIX) && !defined(OS_NACL)
bool MessageLoopForIO::WatchFileDescriptor(int fd,
bool persistent,
Mode mode,
FileDescriptorWatcher *controller,
Watcher *delegate) {
return pump_libevent()->WatchFileDescriptor(
fd,
persistent,
mode,
controller,
delegate);
}
#endif
}