本文主要是介绍MessageQueue创建,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MessageQueue在native层初始化
jlong android_os_MessageQueue_nativeInit(JNIEnv* env,jclass clazz){
NativeMessageQueue* nativeMessageQueue = new NativeMessageQueue();
return reinterpret_cast<jlong>(nativeMessageQueue);
}
当前线程Looper::getForThread()里面拿到局部缓存的looper,
NativeMessageQueue::NativeMessageQueue(){
mLooper = Looper::getForThread();
if(mLooper == NULL){
mLooper = new Looper(flase);
Looper::setForThread(mLooper);
}
}
Looper::getForThread()局部缓存:调用了liunx的接口pthread_getspecific接口
sp<Looper> Looper::getForThread(){
int result = pthread__once(&gTLSOnce,initTLSKey);
return(Looper*)pthread_getspecific(gTLSKey);
}
native层的looper,消息循环的核心部分
Looper::Looper(bool allowNonCallbacks){
mWakeEventFd = eventfd(0,EFD_NONBLOCK);
rebuildEpollLocked();
} eventfd计数器性能比普通管道好
void Looper::rebuildEpollLocked(){
mEpollFd = epoll_create(EPOLL_SIZE_HINT);
struct epoll_event eventltem;
memset(&eventItem,0,sizeof(epoll_event));
eventltem.events = EPOLLIN;
eventltem.data.fd = mWakeEventFd;
epoll_ctl(mEpollFd,EPOLL_CTL_ADD,mWakeEventFd,&eventltem);
......
}
void Looper::wake(){
uint64_t inc = 1;
ssize_t nWrite = write(mWakeEventFd,&inc,sizeof(uint64_t));
}
int Looper::pollOnce(int timeoutMillis,int*outFd,...){
for(::){
polllnner(timeoutMillis);
}
}
polllnner函数的核心是epoll_wait
int Loopet::polllnner(int timeoutMillis){
struct epoll_event eventltems[EPOLL_MAX_EVENTS];
int eventCount = epoll_wait(mEpollFd,eventltems,...);
for(int i=0;i<eventCount;i++){
int fd = eventltems[i].data.fd;
uint32_t epollEvents = eventltems[i].events;
if(fd==mWakeEventFd &&(epollEvents&EPOLLIN)){
awoken();
}
......}......}
awoken读事件,消化事件
void Looper ::awoken(){
uint64_t counter;
read(mWakeEventFd,&counter,sizeof(uint64_t)));
}
}}
这篇关于MessageQueue创建的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!