2015-10-14 160 views
0

我在sender類中有startSending過程和一個好友函數(sending)。我想從一個新線程調用好友功能,所以我在startSending程序中創建了一個新線程。C++無法將參數'1'轉換爲'void *'爲'void *發送(void *)'

class sender{ 
    public: 
    void startSending(); 

    friend void* sending (void * callerobj); 
} 

void sender::startSending(){ 
    pthread_t tSending; 
    pthread_create(&tSending, NULL, sending(*this), NULL); 
    pthread_join(tSending, NULL); 
} 

void* sending (void * callerobj){ 
} 

但我得到這個錯誤

cannot convert ‘sender’ to ‘void*’ for argument ‘1’ to ‘void* sending(void*)’ 

什麼是調用pthread_create的從發送正確的方法是什麼?

+0

據我記得傳遞給pthread_create的方法應該是靜態的。所以像pthread_create(&tSending,NULL,sender :: sending,NULL);宣佈發送靜態。 – redobot

+0

@redobot不是。它不能是一個非靜態的成員函數,但它當然可以是一個自由函數,就像OP的情況一樣。 – Angew

+0

@Angew我沒有檢查文檔。但是如果他想要使用類方法,那麼應該聲明爲靜態的,如果我沒有錯。 – redobot

回答

2

在pthread_create簽名如下所示:

int pthread_create(pthread_t *thread, //irrelevant 
        const pthread_attr_t *attr, //irrelevant 
        void *(*start_routine) (void *), //the pointer to the function that is going to be called 
        void *arg); //the sole argument that will be passed to that function 

所以你的情況,該指針sending必須作爲第三個參數傳遞,並this(將傳遞到sending參數)內斯作爲最後一個參數傳遞:

pthread_create(&tSending, NULL, &sending, this); 
2

按照documentation of pthread_create,你必須在傳遞要執行的功能,而不是它的調用:

pthread_create(&tSending, NULL, &sending, this); 

與該線程將調用該函數被作爲第四個參數傳遞給pthread_create的說法,所以在你的情況下它是this

和(雖然這不是對最常見的平臺上最實用的編譯器實際上是必要的)按規則嚴格去,因爲pthread_create是一個C函數,你發送給它應該有C語言聯動太多的功能:

extern "C" void* sending (void * callerobj){ 
} 
0
pthread_create(&tSending, NULL, sending, this); 

OR

pthread_create(&tSending, NULL, &sending, this); 
相關問題