2014-01-29 18 views
2

當我試圖通過我的功能cleanup_thread()pthread_cleanup_push()沒有匹配的函數調用時傳遞一個類的成員函數pthread_cleanup_push()

pthread_cleanup_push(cleanup_thread, arg); 

我得到以下編譯器錯誤:

error: no matching function for call to ‘__pthread_cleanup_class::__pthread_cleanup_class(<unresolved overloaded function type>, void*&)’ 

我猜是因爲void cleanup_thread(void *arg)是我班的成員函數,因此它有this指針作爲第一個參數。所以函數cleanup_thread()的簽名不匹配。 如何告訴pthread_cleanup_push()使用我的會員功能cleanup_thread()

回答

1

最簡單的解決方案可能是使功能成爲static成員函數,並將實例指針作爲參數傳遞。

事情是這樣的:

struct data_struct 
{ 
    some_class* instance; 
    pthread_t thread_id; 
}; 

class some_class 
{ 
public: 
    ... 

    static void cleanup_thread(void* arg) 
    { 
     data_struct* ptr = reinterpret_cast<data_struct*>(arg); 
     ptr->instance->private_cleanup_thread(); 
     delete ptr; 
    } 

private: 
    void private_cleanup_thread() 
    { 
     ... 
    } 
}; 

... 

some_class* some_class_ptr = new some_class; 

... 

data_struct* data_ptr = new data_struct; 
data_ptr->instance = some_class_ptr; 
data_ptr->thread_id = some_thread_id; 

pthread_cleanup_push(&some_class::cleanup_thread, data_ptr); 
+0

謝謝。另請參閱這裏http://stackoverflow.com/questions/7809987/c-how-to-define-a-class-method-as-a-start-routine-to-thread-with-pthread-lib – tzippy

+0

@tzippy已更新回答 –

+0

但是private_cleanup_thread()函數需要void指針參數void * arg。這是需要清理後的線程。 – tzippy