A brief analysis of thread encapsulation in android

  • 2020-05-17 06:33:04
  • OfStack

Simply write 1 under android for the c++ encapsulation of threads ~ ~ ~ actually API has been written very clearly ~ ~

Encapsulation of file: / / frameworks base/include utils/threads h

We won't talk about the implementation here, but the implementation is system-dependent. First, Anroid provides several functions to create threads directly:


inline bool createThread(thread_func_t f, void *a)  
inline bool createThreadEtc(thread_func_t entryFunction,
                            void *userData,
                            const char* threadName = "android:unnamed_thread",
                            int32_t threadPriority = PRIORITY_DEFAULT,
                            size_t threadStackSize = 0,
                            thread_id_t *threadId = 0)
inline thread_id_t getThreadId()

mutex of Android is basically similar to mutex of posix, except that 1 is added to Mutex::Autolock. This automatic lock is used a lot. If a lock is added to the scope, it will be automatically unlocked when it is removed from the scope.

class Autolock {
    public:
        inline Autolock(Mutex& mutex) : mpMutex(&mutex) { mutex.lock(); }
        inline Autolock(Mutex* mutex) : mpMutex(mutex) { mutex->lock(); }
        inline ~Autolock() { mpMutex->unlock(); }
    private:
        Mutex*  mpMutex;
    };

If you look at Condition of Andorid, the usage of Condition is basically the same as that of posix. Because it is a conditional variable, there is only one mutex parameter ~ ~

Finally, take a look at android's thread class. In the actual use process, they all inherit this thread class to create their own thread class and define the execution content of the thread. The following functions are mainly about the implementation of creating their own thread class:

class Thread : virtual public RefBase
First of all, it inherits from RefBase class. In general, onFirstRef() should be implemented when it is used. The classic usage of Thread is to run run function of Thread in it, so that the thread will be started when an instance of thread is created. It is also possible to start the thread by executing run() instead of run() here.


virtual status_t    run(    const char* name = 0,
                                int32_t priority = PRIORITY_DEFAULT,
                                size_t stack = 0);

When creating an thread instance, the thread is not running, and only when executing the run() function is the thread actually running.

virtual status_t readyToRun();
This function defines the initialization before thread is executed

virtual bool threadLoop() = 0;
If this function returns true, the function will execute threadloop continuously. If this function returns false, the function will execute threadloop only once before the thread exits.


Related articles: