Android Native Thread类分析

在分析Android Nativie 层的代码时,会看到很多相关Thread(线程)的函数,这里分析一下Thread的实现。

Liunx pthread 介绍

在Liunx 中,使用 pthread_create 来创建线程,函数原型如下

//线程创建成功就返回 0
//线程创建成功,调用start_routine 函数,arg为传入函数的参数
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

线程退出

void pthread_exit(void *retval);

比较两个线程的ID是否一致

int pthread_equal(pthread_t t1, pthread_t t2); //返回0表示不相同

join

int pthread_join(pthread_t thread, void **retval); //调用方线程等待thread执行完成

Liunx pthread示例

#include<stdio.h>
#include <pthread.h>
#include <utils/Log.h>
#include <stdlib.h>
/* int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);*/

void *my_thread_func(void *arg){
    int i = 0;
    while(i < 10){
        printf("my thread say i:%d\n",i);
        ALOGD("my thread say i:%d\n",i);
        i++;
    }
    printf("my thread exit!!\n");
    return NULL;
}
int main(){
    //创建线程
    pthread_t my_pthread_t;
    /*返回0表示创建成功*/
    int status = pthread_create(&my_pthread_t,NULL,my_thread_func,NULL);
    if(status){
        printf("my thread create error!!");
        abort();
    }
    //while(1);
    status = pthread_join(my_pthread_t,NULL);//主线程在这里等待子线程执行完毕
    if(status){
        printf("my thread join error!!");
        abort();
    }
    printf("main thread exit!!");

    return 0;
}

Android Native Thread

Android Native Thread也是基于Liunx pthread 的一层封装,源码路径

system\core\libutils\Threads.cpp
system\core\libutils\include\utils\Thread.h

先来看一下Thread.h 头文件的定义

namespace android {
// ---------------------------------------------------------------------------

// DO NOT USE: please use std::thread

class Thread : virtual public RefBase
{
public:
    // Create a Thread object, but doesn't create or start the associated
    // thread. See the run() method.
    explicit            Thread(bool canCallJava = true);
    virtual             ~Thread();

    // Start the thread in threadLoop() which needs to be implemented.
    // NOLINTNEXTLINE(google-default-arguments)
    virtual status_t    run(    const char* name,
                                int32_t priority = PRIORITY_DEFAULT,
                                size_t stack = 0);
    // Ask this object's thread to exit. This function is asynchronous, when the
    // function returns the thread might still be running. Of course, this
    // function can be called from a different thread.
    virtual void        requestExit();

    // Good place to do one-time initializations
    virtual status_t    readyToRun();
    
    // Call requestExit() and wait until this object's thread exits.
    // BE VERY CAREFUL of deadlocks. In particular, it would be silly to call
    // this function from this object's thread. Will return WOULD_BLOCK in
    // that case.
            status_t    requestExitAndWait();

    // Wait until this object's thread exits. Returns immediately if not yet running.
    // Do not call from this object's thread; will return WOULD_BLOCK in that case.
            status_t    join(); //阻塞等待函数
     // Indicates whether this thread is running or not.
            bool        isRunning() const; //判断线程是否正在运行

	#if defined(__ANDROID__)
    	// Return the thread's kernel ID, same as the thread itself calling gettid(),
    	// or -1 if the thread is not running.
            	pid_t       getTid() const;
	#endif

	protected:
    	// exitPending() returns true if requestExit() has been called.
            bool        exitPending() const;
    
	private:
    	// Derived class must implement threadLoop(). The thread starts its life
    	// here. There are two ways of using the Thread object:
    	// 1) loop: if threadLoop() returns true, it will be called again if
    	//          requestExit() wasn't called.
    	// 2) once: if threadLoop() returns false, the thread will exit upon return.
    	virtual bool        threadLoop() = 0;

	//......

可以看出Thread类继承RefBase,所以Thread或者其子类都可以使用智能指针,来看一下Threads.cpp的内部实现。在Nativie层,创建一个Thread实例后,要让Thread运行起来,调用run函数

status_t Thread::run(const char* name, int32_t priority, size_t stack)
{
    LOG_ALWAYS_FATAL_IF(name == nullptr, "thread name not provided to Thread::run");

    Mutex::Autolock _l(mLock);
	//判断是否已经运行
    if (mRunning) {
        // thread already started
        return INVALID_OPERATION;
    }
    // reset status and exitPending to their default value, so we can
    // try again after an error happened (either below, or in readyToRun())
    mStatus = OK;
    mExitPending = false;
    mThread = thread_id_t(-1);

    // hold a strong reference on ourself
    mHoldSelf = this;

    mRunning = true;
    bool res;
    if (mCanCallJava) {//一般为flase
        res = createThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    } else {
        res = androidCreateRawThreadEtc(_threadLoop,
                this, name, priority, stack, &mThread);
    }
    if (res == false) {
        mStatus = UNKNOWN_ERROR;   // something happened!
        mRunning = false;
        mThread = thread_id_t(-1);
        mHoldSelf.clear();  // "this" may have gone away after this.

        return UNKNOWN_ERROR;
    }

    // Do not refer to mStatus here: The thread is already running (may, in fact
    // already have exited with a valid mStatus result). The OK indication
    // here merely indicates successfully starting the thread and does not
    // imply successful termination/execution.
    return OK;
}

先判断该线程是否已经运行,如果已经运行的话,直接返回。然后调用androidCreateRawThreadEtc函数

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_t thread;
    int result = pthread_create(&thread, &attr,
                    (android_pthread_entry)entryFunction, userData);
    pthread_attr_destroy(&attr);
    //......

这里可以看到,Android Native层创建线程也是基于Liunx的pthread_create实现的。调用pthread_create后,开始执行entryFunction函数。entryFunction函数传进来的,是androidCreateRawThreadEtc的第一个参数,即_threadLoop

int Thread::_threadLoop(void* user)
{
	//......
	bool first = true;

    do {
        bool result;
        if (first) {
            first = false;
            self->mStatus = self->readyToRun();
            result = (self->mStatus == OK);

            if (result && !self->exitPending()) {
                result = self->threadLoop();
            }
        } else {
            result = self->threadLoop();
        }
        // establish a scope for mLock
        {
        Mutex::Autolock _l(self->mLock);
        if (result == false || self->mExitPending) {
            self->mExitPending = true;
            self->mRunning = false;
            // clear thread ID so that requestExitAndWait() does not exit if
            // called by a new thread using the same thread ID as this one.
            self->mThread = thread_id_t(-1);
            // note that interested observers blocked in requestExitAndWait are
            // awoken by broadcast, but blocked on mLock until break exits scope
            self->mThreadExitedCondition.broadcast();
            break;
        }
        }

        // Release our strong reference, to let a chance to the thread
        // to die a peaceful death.
        strong.clear();
        // And immediately, re-acquire a strong reference for the next loop
        strong = weak.promote();
    } while(strong != nullptr);

    return 0;
}

_threadLoop 函数体是一个循环,循环体执行的第一次,会调用readyToRun函数,第一次调用时readyToRun返回ture且exitPending为false,会调用threadLoop函数。不是第一次执行循环体的话,会直接调用threadLoop函数。

threadLoop返回false或者mExitPending为true会结束循环,线程结束。

其中mExitPending在调用requestExit 时设置为true

void Thread::requestExit()
{
    Mutex::Autolock _l(mLock);
    mExitPending = true;
}

Android Native Thread 示例

//MyThread.h
#ifndef ANDROID_MYTHREAD_H
#define ANDROID_MYTHREAD_H
#include <utils/Thread.h>
namespace android{
    class MyThread : public Thread
    {
    public:
        MyThread();
        virtual ~MyThread();

    private:
        virtual void        onFirstRef();
        virtual status_t    readyToRun();
        virtual bool        threadLoop();
        int count = 0;
    };
};
#endif

//MyThread.cpp
#include<stdio.h>
#include "MyThread.h"
namespace android {

    MyThread::MyThread() : Thread(false){
        printf("new MyThread!!\n");
    }

    MyThread::~MyThread() {
        printf("desory MyThread!!\n");
    }

    void MyThread::onFirstRef() {
        printf("MyThread onFirstRef!!\n");
    }

    status_t MyThread::readyToRun() {
        printf("MyThread readyToRun!!\n");
        return NO_ERROR;
    }

    bool MyThread::threadLoop() {
        printf("MyThread threadLoop count:%d!!\n",count);
        count++;
        if(count == 10)
            return false;
        return true;
    }
}

//main.cpp
#include<stdio.h>
#include "MyThread.h"
using namespace android;
int main() {
    sp <MyThread> mythread = new MyThread();
    mythread->run("Mythread",PRIORITY_DEFAULT);
//    while(1){
//        if(!mythread->isRunning()){
//            break;
//        }
//    }
    mythread->join();
    printf("main thread is exit!!\n");
    return 0;
}
;

总结

  • Android Native Thread 是基于Liunx 的 pthread 的一层封装
  • Thread 继承RefBase,可以使用智能指针,调用其onFirstRef函数
  • new 一个 Thread 并调用其run函数,可以新建一个线程
  • 创建一个线程后,先调用readyToRun,再调用threadLoop函数
  • threadLoop返回false或者调用过requestExit,线程退出
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于上传限制,附上本书电子版的下载地址,给您带来不便之处,敬请原谅! 《深入理解Android(卷1)》是一本以情景方式对Android的源代码进行深入分析的书。内容广泛,以对Framework层的分析为主,兼顾Native层和Application层;分析深入,每一部分源代码的分析都力求透彻;针对性强,注重实际应用开发需求,书中所涵盖的知识点都是Android应用开发者和系统开发者需要重点掌握的。 《深入理解Android(卷1)》共10章,第1章介绍了阅读本书所需要做的准备工作,主要包括对Android系统架构和源码阅读方法的介绍;第2章通过对Android系统中的MediaScanner进行分析,详细讲解了Android中十分重要的JNI技术;第3章分析了init进程,揭示了通过解析init.rc来启动Zygote以及属性服务的工作原理;第4章分析了Zygote、SystemServer等进程的工作机制,同时还讨论了Android的启动速度、虚拟机HeapSize的大小调整、Watchdog工作原理等问题;第5章讲解了Android系统中常用的,包括sp、wp、RefBase、Thread,同步,以及Java中的Handler和Looper,掌握这些的知识后方能在后续的代码分析中做到游刃有余;第6章以MediaServer为切入点,对Android中极为重要的Binder进行了较为全面的分析,深刻揭示了其本质。第7章对Audio系统进行了深入的分析,尤其是AudioTrack、AudioFlinger和AudioPolicyService等的工作原理。第8章深入讲解了Surface系统的实现原理,分析了Surface与Activity之间以及Surface与SurfaceFlinger之间的关系、SurfaceFlinger的工作原理、Surface系统中的帧数据传输以及LayerBuffer的工作流程。第9章对Vold和Rild的原理和机制进行了深入的分析,同时还探讨了Phone设计优化的问题;第10章分析了多媒体系统中MediaScanner的工作原理。 《深入理解Android(卷1)》适合有一定基础的Android应用开发工程师和系统工程师阅读。通过对本书的学习,大家将能更深刻地理解Android系统,从而自如应对实际开发中遇到的难题。
以下是Android中C++Thread的部分源码,具体实现可以在Android源码中的`frameworks/native/libs/nativebase/include/utils/Thread.h`文件中找到: ```cpp class Thread : public Runnable { public: Thread(); virtual ~Thread(); // Launch a new thread to execute the runnable object. virtual status_t run(const char* name = 0, int32_t priority = PRIORITY_DEFAULT, size_t stack = 0); // Ask the currently running thread to stop. This is called from a different thread. virtual status_t requestExitAndWait(); // Ask the currently running thread to stop. This is called from within the thread to be stopped. virtual status_t requestExit(); // Good place to do one-time initializations. virtual bool threadLoop() = 0; // Return the thread's name. virtual const char* name() const; // Return the thread's priority. virtual int32_t getPriority() const; // Set the thread's priority. virtual status_t setPriority(int32_t priority); // Set the thread's scheduling policy. virtual status_t setSchedulingPolicy(int32_t policy); // Get the thread's scheduling policy. virtual int32_t getSchedulingPolicy() const; // Get the thread's unique identifier. virtual pid_t getTid() const; // Sleeps for the specified number of milliseconds. static void sleep(uint32_t ms); protected: // Exit the thread. virtual void onExit(); // Called before the thread starts executing. virtual bool readyToRun(); // Return the thread's ID. pthread_t id() const; // Return the thread's JNIEnv. JNIEnv* env() const; // Return the thread's JavaVM. JavaVM* javaVM() const; private: class DeathRecipient : public IBinder::DeathRecipient { public: DeathRecipient(Thread* recipient) : mRecipient(recipient) {} virtual ~DeathRecipient() {} virtual void binderDied(const wp<IBinder>& who); private: wp<Thread> mRecipient; }; static int _threadLoop(void* user); int threadLoop(); pthread_t mThread; volatile bool mRunning; volatile bool mExited; bool mNeedToExit; bool mHasStarted; bool mSuccessfullyStartedException; Mutex mLock; Condition mThreadExitedCondition; const char* mName; int32_t mPriority; size_t mStackSize; pid_t mTid; JavaVM* mJavaVM; DeathRecipient* mDeathRecipient; }; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值