主要用到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對象關聯了。android
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 }