IPC thread写法太晦涩
主要用到TLS,首次进入gHaveTLS为false,锁保护说明此函数很多其他函数在调用。
通过if (pthread_key_create(&gTLS, threadDestructor) != 0),中threadDestructor(void *st)
调用IPCThreadState::IPCThreadState()创建IPCThreadState对象,并将对象的索引设置为gTLS。再次进入后通过gTLS获取到IPCThreadState对象。
1 IPCThreadState* IPCThreadState::self() 2 { 3 if (gHaveTLS) { 4 restart: 5 const pthread_key_t k = gTLS; 6 IPCThreadState* st = (IPCThreadState*)pthread_getspecific(k); 7 if (st) return st; 8 return new IPCThreadState; 9 } 10 11 if (gShutdown) return NULL; 12 13 pthread_mutex_lock(&gTLSMutex); 14 if (!gHaveTLS) { 15 if (pthread_key_create(&gTLS, threadDestructor) != 0) { 16 pthread_mutex_unlock(&gTLSMutex); 17 return NULL; 18 } 19 gHaveTLS = true; 20 } 21 pthread_mutex_unlock(&gTLSMutex); 22 goto restart; 23 }
通pthread_setspecific(gTLS, this);gTLS与IPCThreadState对象关联了。
1 IPCThreadState::IPCThreadState() 2 : mProcess(ProcessState::self()), 3 mMyThreadId(androidGetTid()), 4 mStrictModePolicy(0), 5 mLastTransactionBinderFlags(0) 6 { 7 pthread_setspecific(gTLS, this); 8 clearCaller(); 9 mIn.setDataCapacity(256); 10 mOut.setDataCapacity(256); 11 }