C++中編寫線程基礎類,使用線程函數的方法


把成員函數作為線程函數,this指針會作為默認的參數被傳進函數中,從而和線程函數參數(void*)不能匹配,不能通過編譯。怎么解決呢?網上有一個解決辦法,引用過來,自己記着。

摘自:http://hi.chinaunix.net/?uid-11770217-action-viewspace-itemid-48886
將線程函數作為靜態函數,因為在C++中靜態函數沒有this指針(即在內存中靜態函數和普通全局函數幾乎沒有什么區別),故可以匹配編譯通過, 但是當線程函數要訪問私有變量呢?可以訪問到嗎?答案是不可以!

解決方案: 將this指針作為參數傳遞給靜態函數,這樣可以通過該this指針訪問所有的私有變量, 但是我要是還需要向靜態函數中傳遞我自己需要的參數呢?

答案是:將this指針和需要的參數作為一個結構體一起傳給靜態函數,請看下面代碼:

#include <iostream>
#include "pthread.h"
using namespace std;

class A;
struct ARG
{
     A* pThis;
     string var;
};
class A
{
    public:
        A();
        ~A();
        static void* thread(void* args);
        void  excute();
    private:
        int iCount;

};

A::A()
{
    iCount = 10;
}
A::~A()
{

}
void* A::thread(void* args)
{
     ARG *arg = (ARG*)args;
     A* pThis = arg->pThis;
     string var = arg->var;
     cout<<"傳入進來的參數var: "<<var<<endl;
     cout<<"用static線程函數調用私有變量: "<<pThis->iCount<<endl;

}

void A::excute()
{
     int error;
     pthread_t thread_id;
     ARG *arg = new ARG();
     arg->pThis = this;
     arg->var = "abc";
     error = pthread_create(&thread_id, NULL, thread, (void*)arg);
     if (error == 0)
     {
         cout<<"線程創建成功"<<endl;
         pthread_join(thread_id, NULL);
     }
}


免責聲明!

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



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