理解 Android 线程创建流程

基于Android 6.0源码剖析,分析Android线程的创建过程

    /android/libcore/libart/src/main/java/java/lang/Thread.java
    /art/runtime/native/java_lang_Thread.cc
    /art/runtime/native/java_lang_Object.cc
    /art/runtime/thread.cc

    /system/core/libutils/Threads.cpp
    /system/core/include/utils/AndroidThreads.h
    /frameworks/base/core/jni/AndroidRuntime.cpp

一.概述

Android线程,一般地就是指Android虚拟机线程,而虚拟机线程由是通过系统调用而创建的Linux线程。纯粹的Linux线程与虚拟机线程的区别在于虚拟机线程具有运行Java代码的runtime. 除了虚拟机线程,还有Native线程,对于Native线程有分为是否具有访问Java代码的两类线程。接下来,本文分析介绍这3类线程的创建过程。

二. Java线程

2.1 Thread.start

[-> Thread.java]

    public synchronized void start() {
         checkNotStarted(); //保证线程只有启动一次
         hasBeenStarted = true;
         //[见流程2.2]
         nativeCreate(this, stackSize, daemon);
    }

nativeCreate()这是一个native方法,那么其所对应的JNI方法在哪呢?在java_lang_Thread.cc中通过gMethods是一个JNINativeMethod数组,其中一项为:

    NATIVE_METHOD(Thread, nativeCreate, "(Ljava/lang/Thread;JZ)V"),

这里的NATIVE_METHOD定义在java_lang_Object.cc文件,如下:

    #define NATIVE_METHOD(className, functionName, signature) \
        { #functionName, signature, reinterpret_cast<void*>(className ## _ ## functionName) }

将宏定义展开并代入,可得所对应的方法名为Thread_nativeCreate,那么接下来进入该方法。

2.2 Thread_nativeCreate

[-> java_lang_Thread.cc]

    static void Thread_nativeCreate(JNIEnv* env, jclass, jobject java_thread, 
                                      jlong stack_size, jboolean daemon) {
      //【见小节2.3】
      Thread::CreateNativeThread(env, java_thread, stack_size, daemon == JNI_TRUE);
    }

2.3 CreateNativeThread

[-> thread.cc]

    void Thread::CreateNativeThread(JNIEnv* env, jobject java_peer, size_t stack_size, bool is_daemon) {
      Thread* self = static_cast<JNIEnvExt*>(env)->self;
      Runtime* runtime = Runtime::Current();

      ...
      Thread* child_thread = new Thread(is_daemon);
      child_thread->tlsPtr_.jpeer = env->NewGlobalRef(java_peer);
      stack_size = FixStackSize(stack_size);

      env->SetLongField(java_peer, WellKnownClasses::java_lang_Thread_nativePeer,
                        reinterpret_cast<jlong>(child_thread));

      std::unique_ptr<JNIEnvExt> child_jni_env_ext(
          JNIEnvExt::Create(child_thread, Runtime::Current()->GetJavaVM()));

      int pthread_create_result = 0;
      if (child_jni_env_ext.get() != nullptr) {
        pthread_t new_pthread;
        pthread_attr_t attr;
        child_thread->tlsPtr_.tmp_jni_env = child_jni_env_ext.get();
        //创建线程【见小节2.4】
        pthread_create_result = pthread_create(&new_pthread,
                             &attr, Thread::CreateCallback, child_thread);

        if (pthread_create_result == 0) {
          child_jni_env_ext.release();
          return;
        }
      }

      ...
    }

2.4 pthread_create

pthread_create是pthread库中的函数,通过syscall再调用到clone来请求内核创建线程。

  • 原型:int pthread_create((pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
  • 头文件:#include <pthread.h>
  • 输入参数:thread:线程标识符; attr:线程属性设置; start_routine:线程函数的起始地址; arg:传递给start_routine的参数;
  • 返回值:成功则返回0;出错则返回-1。
  • 功能:创建线程,并调用线程起始地址所指向的函数start_routine。

关于pthread_create的分析,在后续Linux系列文章会再进一步深入分析。

三. Native线程(C/C++)

3.1 Thread.run

[-> Threads.cpp]

    status_t Thread::run(const char* name, int32_t priority, size_t stack)
    {
        Mutex::Autolock _l(mLock);
        //保证只会启动一次
        if (mRunning) {
            return INVALID_OPERATION;
        }
        ...
        mRunning = true;

        bool res;

        if (mCanCallJava) {
            //还能调用Java代码的Native线程【见小节4.1】
            res = createThreadEtc(_threadLoop,
                    this, name, priority, stack, &mThread);
        } else {
            //只能调用C/C++代码的Native线程【见小节3.2】
            res = androidCreateRawThreadEtc(_threadLoop,
                    this, name, priority, stack, &mThread);
        }

        if (res == false) {
            ...//清理
            return UNKNOWN_ERROR;
        }
        return NO_ERROR;
    }

mCanCallJava在Thread对象创建时,在构造函数中默认设置mCanCallJava=true.

  • 当mCanCallJava=true,则代表创建的是不仅能调用C/C++代码,还能能调用Java代码的Native线程
  • 当mCanCallJava=false,则代表创建的是只能调用C/C++代码的Native线程。

3.2 androidCreateRawThreadEtc

[-> Threads.cpp]

    int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
                                   void *userData,
                                   const char* threadName __android_unused,
                                   int32_t threadPriority,
                                   size_t threadStackSize,
                                   android_thread_id_t *threadId)
    {
        pthread_attr_t attr;
        pthread_attr_init(&attr);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

        if (threadPriority != PRIORITY_DEFAULT || threadName != NULL) {
            thread_data_t* t = new thread_data_t;
            t->priority = threadPriority;
            t->threadName = threadName ? strdup(threadName) : NULL;
            t->entryFunction = entryFunction;
            t->userData = userData;
            entryFunction = (android_thread_func_t)&thread_data_t::trampoline;
            userData = t;
        }

        if (threadStackSize) {
            pthread_attr_setstacksize(&attr, threadStackSize);
        }

        errno = 0;
        pthread_t thread;
        //通过pthread_create创建线程
        int result = pthread_create(&thread, &attr,
                        (android_pthread_entry)entryFunction, userData);
        pthread_attr_destroy(&attr);
        if (result != 0) {
            ... //创建失败,则返回
            return 0;
        }

        if (threadId != NULL) {
            *threadId = (android_thread_id_t)thread; 
        }
        return 1;
    }

此处entryFunction所指向的是由[小节3.1]传递进来的,其值为_threadLoop。

3.3 _threadLoop

[-> Threads.cpp]

    int Thread::_threadLoop(void* user)
    {
        //user是指Thread对象
        Thread* const self = static_cast<Thread*>(user);

        sp<Thread> strong(self->mHoldSelf);
        wp<Thread> weak(strong);
        self->mHoldSelf.clear();

        //该参数对于gdb调试很有作用
        self->mTid = gettid();

        bool first = true;
        do {
            bool result;
            if (first) {
                first = false;
                //首次运行时会调用readyToRun()做一些初始化准备工作
                self->mStatus = self->readyToRun();
                result = (self->mStatus == NO_ERROR);
                if (result && !self->exitPending()) {
                    //
                    result = self->threadLoop();
                }
            } else {
                result = self->threadLoop();
            }

            {
              Mutex::Autolock _l(self->mLock);
              if (result == false || self->mExitPending) {
                  self->mExitPending = true;
                  self->mRunning = false;
                  self->mThread = thread_id_t(-1);
                  self->mThreadExitedCondition.broadcast();
                  break;
              }
            }
top Created with Sketch.