2012-10-19 35 views
1

可能重複:
pthread Function from a ClassG ++錯誤:在pthread_create()和成員函數指針

我試圖創建一個啓動程序的線程,但G ++不喜歡我句法。

class myClass 
{ 
    void* myFunction(void* myArg) 
    { 
    // some code, useless here 
    } 

    void start() 
    { 
    pthread_t thread_id; 
    int* fd; 

    //Some code, useless here. 

    pthread_create(&thread_id, 0, &myFunction, (void*) fd); 
    } 
} 

在編譯器中,g ++告訴我,ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&myFunction'

對於參數3 pthread_create,它不能將void (myClass::*) (void*)轉換爲void* (*) (void*)

有什麼想法?

回答

1

您需要將myFunction聲明爲靜態,才能將其視爲常規函數。

0

您不能使用普通函數成員作爲線程例程。原因是這樣的函數成員需要調用上下文 - this對象指針,它不可用於pthread膽量。

使這樣的功能成員static或只是免費的功能。

0

您無法傳遞指向非靜態方法的指針。你可能想要使用代理函數,將指針傳遞給你的實例作爲pthread_create的參數,並從那裏進行myFunction調用

0

由於編譯器說你必須在pthread中使用靜態函數,所以應該這樣工作:

class myClass 
{ 
    static void startThread(void* context) 
    { 
    ((myClass*)context)->myFunction() 
    } 

    void myFunction() 
    { 
    // some code, useless here 
    } 

    void start() 
    { 
    pthread_t thread_id; 

    //Some code, useless here. 

    pthread_create(&thread_id, 0, &startThread, this); 
    } 
} 

您也可以使用結構爲,其中,如果需要,您可以通過這個和其他參數的情況下。

0

您可以使您的函數成爲靜態函數,也可以使用一些小的解決方法從您的類中調用函數。

void *callMyFunction(void *f) 
{ 
    reinterpret_cast<myClass*>(f)->myFunction(); 
    return (NULL); 
} 

class myClass 
{ 
    void* myFunction() 
    { 
    // some code, useless here 
    } 

    void start() 
    { 
    pthread_t thread_id; 
    int* fd; 

    //Some code, useless here. 

    pthread_create(&thread_id, 0, &callMyFunction, (void*) this); 
    } 
} 

如果你想傳遞參數給myClass::myFunction,你需要創建一個小的結構是這樣

struct s_param 
{ 
    void *ptr; 
    int param1; 
    char param2; 
    /* other variables */ 
}; 

callMyFunction將成爲

void *callMyFunction(void *bundle) 
    { 
     reinterpret_cast<myClass*>(bundle->ptr)->myFunction(bundle->param1, bundle->param2/*, ...*/); 
     return (NULL); 
    } 
0

正如你的編譯器指定pthread_create期待一個void* (*)(void*)但你提供了一個非常相似但語法不同的函數:

一類是不static有一個名爲class*類型的this隱藏參數的每個功能,所以現在你的函數是void* (*)(class*, void*)不是由pthread_create期待的一場比賽。您應該提供具有相同體系結構的功能。

此外,如果您的課程中有類似void* someFunction()的功能,它可能與pthread_create預期的函數匹配,當然這不是編譯器允許的,它也有一個原因。原因是調用約定,這意味着如何將參數傳遞給函數,C++編譯器允許在寄存器中傳遞this!所以它不會與pthread_create預期的功能相匹配。這可以通過一些編譯器,讓您選擇調用你的函數的約定來解決,但它不是標準的,所以最好的辦法是寫一個代理功能:

static void* my_thread_routine_proxy(void* param) { 
    static_cast<my_class*>(param)->my_thread_routine(); 
} 

但是如果你需要更多參數傳遞你應該爲它創建一個結構並在那個結構中傳遞你的參數,但是不要記住,直到你的函數實際上被稱爲一個新線程,傳遞的結構必須保持有效。所以它應該是一個全局或動態分配的對象