From 5d6755466d1876113f05c231252653b6e4fd6421 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Sat, 28 Mar 2020 16:55:47 +0800 Subject: [PATCH] =?UTF-8?q?Create=20=E6=B6=88=E6=81=AF=E9=98=9F=E5=88=97?= =?UTF-8?q?=E5=88=9B=E5=BB=BA.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../线程通信相关/消息队列创建.md | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 blogs/Android/Framework/Interview/线程通信相关/消息队列创建.md diff --git a/blogs/Android/Framework/Interview/线程通信相关/消息队列创建.md b/blogs/Android/Framework/Interview/线程通信相关/消息队列创建.md new file mode 100644 index 0000000..e4133f2 --- /dev/null +++ b/blogs/Android/Framework/Interview/线程通信相关/消息队列创建.md @@ -0,0 +1,69 @@ +--- +线程的消息队列是怎么创建的? +--- + +1. 可以在子线程创建 handler 嘛? +2. 主线程的 Looper 和子线程的 Looper 有什么区别? +3. Looper 的 MessageQueue 有什么关系? +4. MessageQueue 是怎么创建的? + +NativeMessageQueue: + +```c++ +jlong MessageQueue_nativeInit(JNIEnv* env, jclass clazz){ + NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue(); + return reinterpret_cast(nativeMessageQueue); +} +NativeMessageQueue::NativeMessageQueue(){ + mLooper = Looper::getForThread(); + if(mLooper == NULL){ + mLooper = new Looper(false); + Looper::setForThread(mLooper); + } +} +sp Looper::getForThread(){ + int result = pthread_once(& gTLSOnce, initTLSKey); + return (Looper*)pthread_getspecific(gTLSKey); +} +``` + +Native Looper: + +```c++ +Looper::Looper(bool allowNonCallbacks){ + mWakeEventFd = eventfd(0, EFD_NONBLOCK); + rebuildEpollLocked(); +} +void Looper::rebuildEpollLocked(){ + mEpollFd = epoll_create(EPOLL_SIZE_HINT); + struct epoll_event eventItem; + memset(& eventItem, 0, sizeof(epoll_event)); + eventItem.events = EPOLLIN; + eventItem.data.fd = mWakeEventFd; + epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mWakeEventFd, & eventItem); +} +void Looper::wake(){ + uint64_t inc = 1; + ssize_t nWrite = write(mWakeEventFd, &inc, sizeof(uint64_t)); +} +int Looper::pollOnce(int timeoutMillis, int* outFd, ...){ + for(;;){ + pollInner(timeoutMillis); + } +} +int Looper::pollInner(int timeoutMillis){ + struct epoll_event eventItems[EPOLL_MAX_EVENTS]; + int eventCount = epoll_wait(mEpollFd, eventItems, ...); + for(int i=0;i