Android Looper原理ソース分析
17441 ワード
概要
ずいぶん前に「Android Message Queue、Message、Looper、Handler」という小さな記事を転載し、Android Message Queue、Looper、Handlerという概念の関係を紹介しました.その中でLooperはこのいくつかの概念の核心に位置し、1つのLooperの中にMessageQueueがあります.複数のHandlerは1つのLooperを共有することができ、1つのスレッドには1つのLooperしかありません.今日はLooperの原理ソースコードを詳しく分析します
ソース位置
frameworks/native/lib/utils/Looper.cpp
Looper.h
Lopperの原理
Looperイベントメカニズムは,実際にはシステム呼び出しepollに依存して実現される.複数のI/Oイベントを同時に監視できるI/O多重モデルです.Looperにとって、I/Oイベントとは、監視されているファイル記述子にデータが到着していないことです.メッセージが到着しないとスレッドはスリープ状態にあり,メッセージが到着したらメッセージを処理する.
Looper構造と解析
コンストラクション関数では、mWakeReadPipeFd、mWakeWritePipeFd、およびmEpollFdを構築することが最も重要です.解析関数では3つを解析しています.ここで、mWakeReadPipeFdとmWakeWritePipeFdは双方向パイプの両端であり、次にepollインスタンスを作成し、読み取り専用パイプファイル記述子をepollの監視リストに追加する.
Looperコアメソッド
Androidアプリケーション層のLooperループがMessageを取得して処理する場合(message)queue.next()は、最終的にnativeレイヤのLooperに呼び出されます.PollInnterメソッド.最終的にはこの行のコードint eventCount=epoll_に実行されます.wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis); epoll_waitは、コンストラクション関数で初期化されたepollインスタンスに登録されたファイル記述子を傍受するためのIO読み書きイベントである.このファイル記述子にIO読み書きイベントが発生しない場合、現在のスレッドはepoll_になります.waitでは睡眠待ち状態に入り、待ち時間が長いtimeoutMillis.
epoll_wait目覚ましタイミング
上記の現在のスレッドを除いてepoll_waitでは睡眠待ち状態に入り、待ち時間が長くなるとtimeoutMillisが目を覚ます.もう一つの目覚めのタイミングは、新しいMessageを送信することです.このメッセージがdelayを必要としない場合は、直接起動します.delayがあり、メッセージキューのヘッダ(すなわち、最新の起動時間が更新された)が変化した場合にも、起動が行われる.
に感謝
http://blog.ifjy.me/android/2016/07/16/Looper類分析html https://android.googlesource.com/platform/frameworks/native/+/jb-dev/libs/utils/Looper.cpp https://baike.baidu.com/item/epoll/10738144
ずいぶん前に「Android Message Queue、Message、Looper、Handler」という小さな記事を転載し、Android Message Queue、Looper、Handlerという概念の関係を紹介しました.その中でLooperはこのいくつかの概念の核心に位置し、1つのLooperの中にMessageQueueがあります.複数のHandlerは1つのLooperを共有することができ、1つのスレッドには1つのLooperしかありません.今日はLooperの原理ソースコードを詳しく分析します
ソース位置
frameworks/native/lib/utils/Looper.cpp
Looper.h
class Looper : public ALooper, public RefBase {
protected:
virtual ~Looper();
public:
/**
* Creates a looper.
*
* If allowNonCallbaks is true, the looper will allow file descriptors to be
* registered without associated callbacks. This assumes that the caller of
* pollOnce() is prepared to handle callback-less events itself.
*/
Looper(bool allowNonCallbacks);
/**
* Returns whether this looper instance allows the registration of file descriptors
* using identifiers instead of callbacks.
*/
bool getAllowNonCallbacks() const;
/**
* Waits for events to be available, with optional timeout in milliseconds.
* Invokes callbacks for all file descriptors on which an event occurred.
*
* If the timeout is zero, returns immediately without blocking.
* If the timeout is negative, waits indefinitely until an event appears.
*
* Returns ALOOPER_POLL_WAKE if the poll was awoken using wake() before
* the timeout expired and no callbacks were invoked and no other file
* descriptors were ready.
*
* Returns ALOOPER_POLL_CALLBACK if one or more callbacks were invoked.
*
* Returns ALOOPER_POLL_TIMEOUT if there was no data before the given
* timeout expired.
*
* Returns ALOOPER_POLL_ERROR if an error occurred.
*
* Returns a value >= 0 containing an identifier if its file descriptor has data
* and it has no callback function (requiring the caller here to handle it).
* In this (and only this) case outFd, outEvents and outData will contain the poll
* events and data associated with the fd, otherwise they will be set to NULL.
*
* This method does not return until it has finished invoking the appropriate callbacks
* for all file descriptors that were signalled.
*/
int pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData);
inline int pollOnce(int timeoutMillis) {
return pollOnce(timeoutMillis, NULL, NULL, NULL);
}
/**
* Like pollOnce(), but performs all pending callbacks until all
* data has been consumed or a file descriptor is available with no callback.
* This function will never return ALOOPER_POLL_CALLBACK.
*/
int pollAll(int timeoutMillis, int* outFd, int* outEvents, void** outData);
inline int pollAll(int timeoutMillis) {
return pollAll(timeoutMillis, NULL, NULL, NULL);
}
/**
* Wakes the poll asynchronously.
*
* This method can be called on any thread.
* This method returns immediately.
*/
void wake();
/**
* Adds a new file descriptor to be polled by the looper.
* If the same file descriptor was previously added, it is replaced.
*
* "fd" is the file descriptor to be added.
* "ident" is an identifier for this event, which is returned from pollOnce().
* The identifier must be >= 0, or ALOOPER_POLL_CALLBACK if providing a non-NULL callback.
* "events" are the poll events to wake up on. Typically this is ALOOPER_EVENT_INPUT.
* "callback" is the function to call when there is an event on the file descriptor.
* "data" is a private data pointer to supply to the callback.
*
* There are two main uses of this function:
*
* (1) If "callback" is non-NULL, then this function will be called when there is
* data on the file descriptor. It should execute any events it has pending,
* appropriately reading from the file descriptor. The 'ident' is ignored in this case.
*
* (2) If "callback" is NULL, the 'ident' will be returned by ALooper_pollOnce
* when its file descriptor has data available, requiring the caller to take
* care of processing it.
*
* Returns 1 if the file descriptor was added, 0 if the arguments were invalid.
*
* This method can be called on any thread.
* This method may block briefly if it needs to wake the poll.
*
* The callback may either be specified as a bare function pointer or as a smart
* pointer callback object. The smart pointer should be preferred because it is
* easier to avoid races when the callback is removed from a different thread.
* See removeFd() for details.
*/
int addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data);
int addFd(int fd, int ident, int events, const sp& callback, void* data);
/**
* Removes a previously added file descriptor from the looper.
*
* When this method returns, it is safe to close the file descriptor since the looper
* will no longer have a reference to it. However, it is possible for the callback to
* already be running or for it to run one last time if the file descriptor was already
* signalled. Calling code is responsible for ensuring that this case is safely handled.
* For example, if the callback takes care of removing itself during its own execution either
* by returning 0 or by calling this method, then it can be guaranteed to not be invoked
* again at any later time unless registered anew.
*
* A simple way to avoid this problem is to use the version of addFd() that takes
* a sp instead of a bare function pointer. The LooperCallback will
* be released at the appropriate time by the Looper.
*
* Returns 1 if the file descriptor was removed, 0 if none was previously registered.
*
* This method can be called on any thread.
* This method may block briefly if it needs to wake the poll.
*/
int removeFd(int fd);
/**
* Enqueues a message to be processed by the specified handler.
*
* The handler must not be null.
* This method can be called on any thread.
*/
void sendMessage(const sp& handler, const Message& message);
/**
* Enqueues a message to be processed by the specified handler after all pending messages
* after the specified delay.
*
* The time delay is specified in uptime nanoseconds.
* The handler must not be null.
* This method can be called on any thread.
*/
void sendMessageDelayed(nsecs_t uptimeDelay, const sp& handler,
const Message& message);
/**
* Enqueues a message to be processed by the specified handler after all pending messages
* at the specified time.
*
* The time is specified in uptime nanoseconds.
* The handler must not be null.
* This method can be called on any thread.
*/
void sendMessageAtTime(nsecs_t uptime, const sp& handler,
const Message& message);
/**
* Removes all messages for the specified handler from the queue.
*
* The handler must not be null.
* This method can be called on any thread.
*/
void removeMessages(const sp& handler);
/**
* Removes all messages of a particular type for the specified handler from the queue.
*
* The handler must not be null.
* This method can be called on any thread.
*/
void removeMessages(const sp& handler, int what);
/**
* Prepares a looper associated with the calling thread, and returns it.
* If the thread already has a looper, it is returned. Otherwise, a new
* one is created, associated with the thread, and returned.
*
* The opts may be ALOOPER_PREPARE_ALLOW_NON_CALLBACKS or 0.
*/
static sp prepare(int opts);
/**
* Sets the given looper to be associated with the calling thread.
* If another looper is already associated with the thread, it is replaced.
*
* If "looper" is NULL, removes the currently associated looper.
*/
static void setForThread(const sp& looper);
/**
* Returns the looper associated with the calling thread, or NULL if
* there is not one.
*/
static sp getForThread();
private:
struct Request {
int fd;
int ident;
sp callback;
void* data;
};
struct Response {
int events;
Request request;
};
struct MessageEnvelope {
MessageEnvelope() : uptime(0) { }
MessageEnvelope(nsecs_t uptime, const sp handler,
const Message& message) : uptime(uptime), handler(handler), message(message) {
}
nsecs_t uptime;
sp handler;
Message message;
};
const bool mAllowNonCallbacks; // immutable
int mWakeReadPipeFd; // immutable
int mWakeWritePipeFd; // immutable
Mutex mLock;
Vector mMessageEnvelopes; // guarded by mLock
bool mSendingMessage; // guarded by mLock
int mEpollFd; // immutable
// Locked list of file descriptor monitoring requests.
KeyedVector mRequests; // guarded by mLock
// This state is only used privately by pollOnce and does not require a lock since
// it runs on a single thread.
Vector mResponses;
size_t mResponseIndex;
nsecs_t mNextMessageUptime; // set to LLONG_MAX when none
int pollInner(int timeoutMillis);
void awoken();
void pushResponse(int events, const Request& request);
static void initTLSKey();
static void threadDestructor(void *st);
};
Lopperの原理
Looperイベントメカニズムは,実際にはシステム呼び出しepollに依存して実現される.複数のI/Oイベントを同時に監視できるI/O多重モデルです.Looperにとって、I/Oイベントとは、監視されているファイル記述子にデータが到着していないことです.メッセージが到着しないとスレッドはスリープ状態にあり,メッセージが到着したらメッセージを処理する.
Looper構造と解析
コンストラクション関数では、mWakeReadPipeFd、mWakeWritePipeFd、およびmEpollFdを構築することが最も重要です.解析関数では3つを解析しています.ここで、mWakeReadPipeFdとmWakeWritePipeFdは双方向パイプの両端であり、次にepollインスタンスを作成し、読み取り専用パイプファイル記述子をepollの監視リストに追加する.
Looper::Looper(bool allowNonCallbacks) :
mAllowNonCallbacks(allowNonCallbacks), mSendingMessage(false),
mResponseIndex(0), mNextMessageUptime(LLONG_MAX) {
int wakeFds[2];
int result = pipe(wakeFds);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not create wake pipe. errno=%d", errno);
mWakeReadPipeFd = wakeFds[0];
mWakeWritePipeFd = wakeFds[1];
result = fcntl(mWakeReadPipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake read pipe non-blocking. errno=%d",
errno);
result = fcntl(mWakeWritePipeFd, F_SETFL, O_NONBLOCK);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not make wake write pipe non-blocking. errno=%d",
errno);
// Allocate the epoll instance and register the wake pipe.
mEpollFd = epoll_create(EPOLL_SIZE_HINT);
LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
struct epoll_event eventItem;
memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union
eventItem.events = EPOLLIN;
eventItem.data.fd = mWakeReadPipeFd;
result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeReadPipeFd, & eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add wake read pipe to epoll instance. errno=%d",
errno);
}
Looper::~Looper() {
close(mWakeReadPipeFd);
close(mWakeWritePipeFd);
close(mEpollFd);
}
Looperコアメソッド
Androidアプリケーション層のLooperループがMessageを取得して処理する場合(message)queue.next()は、最終的にnativeレイヤのLooperに呼び出されます.PollInnterメソッド.最終的にはこの行のコードint eventCount=epoll_に実行されます.wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis); epoll_waitは、コンストラクション関数で初期化されたepollインスタンスに登録されたファイル記述子を傍受するためのIO読み書きイベントである.このファイル記述子にIO読み書きイベントが発生しない場合、現在のスレッドはepoll_になります.waitでは睡眠待ち状態に入り、待ち時間が長いtimeoutMillis.
int Looper::pollInner(int timeoutMillis) {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);
#endif
// Adjust the timeout based on when the next message is due.
if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);
if (messageTimeoutMillis >= 0
&& (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {
timeoutMillis = messageTimeoutMillis;
}
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",
this, mNextMessageUptime - now, timeoutMillis);
#endif
}
// Poll.
int result = ALOOPER_POLL_WAKE;
mResponses.clear();
mResponseIndex = 0;
struct epoll_event eventItems[EPOLL_MAX_EVENTS];
int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
// Acquire lock.
mLock.lock();
// Check for poll error.
if (eventCount < 0) {
if (errno == EINTR) {
goto Done;
}
ALOGW("Poll failed with an unexpected error, errno=%d", errno);
result = ALOOPER_POLL_ERROR;
goto Done;
}
// Check for poll timeout.
if (eventCount == 0) {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - timeout", this);
#endif
result = ALOOPER_POLL_TIMEOUT;
goto Done;
}
// Handle all events.
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);
#endif
for (int i = 0; i < eventCount; i++) {
int fd = eventItems[i].data.fd;
uint32_t epollEvents = eventItems[i].events;
if (fd == mWakeReadPipeFd) {
if (epollEvents & EPOLLIN) {
awoken();
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);
}
} else {
ssize_t requestIndex = mRequests.indexOfKey(fd);
if (requestIndex >= 0) {
int events = 0;
if (epollEvents & EPOLLIN) events |= ALOOPER_EVENT_INPUT;
if (epollEvents & EPOLLOUT) events |= ALOOPER_EVENT_OUTPUT;
if (epollEvents & EPOLLERR) events |= ALOOPER_EVENT_ERROR;
if (epollEvents & EPOLLHUP) events |= ALOOPER_EVENT_HANGUP;
pushResponse(events, mRequests.valueAt(requestIndex));
} else {
ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "
"no longer registered.", epollEvents, fd);
}
}
}
epoll_wait目覚ましタイミング
上記の現在のスレッドを除いてepoll_waitでは睡眠待ち状態に入り、待ち時間が長くなるとtimeoutMillisが目を覚ます.もう一つの目覚めのタイミングは、新しいMessageを送信することです.このメッセージがdelayを必要としない場合は、直接起動します.delayがあり、メッセージキューのヘッダ(すなわち、最新の起動時間が更新された)が変化した場合にも、起動が行われる.
void Looper::sendMessageAtTime(nsecs_t uptime, const sp& handler,
const Message& message) {
#if DEBUG_CALLBACKS
ALOGD("%p ~ sendMessageAtTime - uptime=%lld, handler=%p, what=%d",
this, uptime, handler.get(), message.what);
#endif
size_t i = 0;
{ // acquire lock
AutoMutex _l(mLock);
size_t messageCount = mMessageEnvelopes.size();
while (i < messageCount && uptime >= mMessageEnvelopes.itemAt(i).uptime) {
i += 1;
}
MessageEnvelope messageEnvelope(uptime, handler, message);
mMessageEnvelopes.insertAt(messageEnvelope, i, 1);
// Optimization: If the Looper is currently sending a message, then we can skip
// the call to wake() because the next thing the Looper will do after processing
// messages is to decide when the next wakeup time should be. In fact, it does
// not even matter whether this code is running on the Looper thread.
if (mSendingMessage) {
return;
}
} // release lock
// Wake the poll loop only when we enqueue a new message at the head.
if (i == 0) {
wake();
}
}
void Looper::wake() {
#if DEBUG_POLL_AND_WAKE
ALOGD("%p ~ wake", this);
#endif
ssize_t nWrite;
do {
nWrite = write(mWakeWritePipeFd, "W", 1);
} while (nWrite == -1 && errno == EINTR);
if (nWrite != 1) {
if (errno != EAGAIN) {
ALOGW("Could not write wake signal, errno=%d", errno);
}
}
}
に感謝
http://blog.ifjy.me/android/2016/07/16/Looper類分析html https://android.googlesource.com/platform/frameworks/native/+/jb-dev/libs/utils/Looper.cpp https://baike.baidu.com/item/epoll/10738144