2013-12-21 21 views
0

我有以下的C代碼:pthread_cleanup_push與調用pthread_mutex_unlock

pthread_cleanup_push(pthread_mutex_unlock, &mutex); 

但是當我編譯它,我得到以下警告:

warning: initialization from incompatible pointer type 

有什麼不對?它看起來像清理處理程序應該返回void *,而不是int。有沒有辦法繞過這個警告,而不寫另外的包裝?

+0

這是一個非常明確的警告。你與什麼部分糾纏?您是否閱讀過這裏涉及的所有函數的手冊? –

+0

可能[duplicate](http://stackoverflow.com/questions/6119140/c-gcc-warning-initialization-from-incompatible-pointer-type-when-calling-pthr) – Hariprasad

+0

你們倆都錯過了實際的問題。 –

回答

4

表達式pthread_mutex_unlock沒有類型void (*)(void *)。您需要將其包裝:

static void cleanup_unlock_mutex(void *p) 
{ 
    pthread_mutex_unlock(p); 
} 

並將此函數的地址傳遞給pthread_cleanup_push

其他人可能會建議你只投pthread_mutex_unlock,但這是不正確的和不安全的。它將導致函數通過指向錯誤函數類型的指針被調用,導致未定義的行爲。