gogoWebsite

C++ Thread Usage in Android (57)

Updated to 3 hours ago

 1. Android encapsulates Thread class with C++, which is the base class of threads

2. When using Thread, create a class inherited from the Thread class. The threadLoop() method is a pure virtual function, which is implemented in a subclass.

3. Start the thread and call the run() function

class Thread : virtual public RefBase//RefBase encapsulates sp, wp smart pointers
{
public:
                        Thread(bool canCallJava = true);
                        virtual             ~Thread();

                       // Start the thread, create a new thread and execute the threadLoop() virtual function

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

                      //Exit thread function (asynchronous)
                        virtual void        requestExit();

                       /*readyToRun() in Android 4.4 version system/core/libutils/,

                         existrun()In the function_threadLoop()Method is calledself->readyToRun();Initialize thread,

                         Called afterwardresult = self->threadLoop();Really start the thread */

                       // This virtual function can be overloaded for initialization, and is an implicit call
                        virtual status_t    readyToRun();
    
                     //Thread exit (synchronization)
                        status_t    requestExitAndWait();
protected:
                       // Determine whether requestExit() has been called.
                        bool        exitPending() const;
    
private:

                    // Thread function. If this function returns true, the function will be called again when requestExit() has not been called; if false is returned,
                         The thread exits when the function returns

virtual bool             threadLoop() = 0;//Pure virtual function, implemented in subclasses

};

For example:

The Thread class inherits from the ReBase virtual base class, new a sp template class, and will eventually call onFirstRef() overloaded by this class object on Refbase;
For example:sp<MainThread> mMainThread; //Member variable; Smart pointer sp<char> == char *Equivalent
mMainThread = newMainThread();//new A template class of sp is assigned to member variablesmMainThread
The onFirstRef() method in the virtual base class Refbase() is called. At this time, the opposite run() message is called, the thread starts, and threadLoop() is called continuously and threadLoop() is executed continuously.

class MainThread : public Thread {
public:
    MainThread();
    virtual  ~MainThread();
    virtual void onFirstRef() 

    {

        run("MainThread", PRIORITY_DEFAULT);
    }
    virtual status_t  readyToRun();
    virtual bool threadLoop();
    virtual void     requestExit();
    void requestLock();

private:
    sp<MainThread> mMainThread;
  
};