linux 之 pthread_create 實現類的成員函數做參數


        在C++的類中,普通成員函數不能作為pthread_create的線程函數,如果要作為pthread_create中的線程函數,必須是static !

        在C語言中,我們使用pthread_create創建線程,線程函數是一個全局函數,所以在C++中,創建線程時,也應該使用一個全局函數。static定義的類的成員函數就是一個全局函數。

class Thread
{
    private:
        pthread_t pid;
    private:
        static void * start_thread(void *arg) //靜態成員函數只能訪問靜態變量或靜態函數,通過傳遞this指針進行調用
        {
            Thread *ptr = (Thread *)arg;
            ptr->fpConnectionRunning();  //線程的實體是run
        }
    public: 
        int start()
        {
            if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0) //´創建一個線程(必須是全局函數)
            {    
                return -1; 
            }    
            return 0;
        }
        
        virtual void fpConnectionRunning() = 0; //基類中的虛函數要么實現,要么是純虛函數(絕對不允許聲明不實現,也不純虛)
};

class SlamData:public Thread
{

public:
    SlamData(){
            if(start()==-1){        
            std::cout<<"pthread_create error ..."<<std::endl;
          }
        }
    ~SlamData();
    
    void fpConnectionRunning();  //實現fpConnectionRunning
        
};

                

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM