2012-12-19 40 views
3

我有以下幾點:編譯警告返回用了pthread_exit()RETVAL當

void *Thrd(void *data) 
{ 
    int ret; 
    ret = myfunc(); 
    pthread_exit((void *)ret); 
} 

int main(int argc, char *argv[]) 
{ 
    int status; 

    pthread_create(&Thread, NULL, Thrd, &data); 

    pthread_join(txThread, (void **)&status); 
    if (status) 
     printf("*** thread failed with error %d\n", status); 
} 

它的工作原理,我能讀狀態但我發現下面的警告在編譯:

test.cpp: In function ‘void* Thrd(void*)’: 
test.cpp:468:26: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 

這是與線pthread_exit()

我根本就看不到什麼是錯:(...

+0

你怎麼沒發現什麼是錯的。編譯器告訴你:「從不同大小的整數轉換爲指針」。什麼是很難理解? –

回答

0

取而代之的是:

pthread_exit((void *)ret); 

這樣寫:

pthread_exit((void *)&ret); 

在 「了pthread_exit((無效*)RET)」,你告訴pthread_exit有地址pertaining to the value contained in ret variable返回值。你希望結果存儲在ret的地址,所以它應該是pthread_exit(&ret)

現在ret是一個局部整數變量。它最好寫如下:

int *ret=malloc(sizeof(int)); 

if(ret==NULL) 

    //handle the error 

*ret=func(); 

pthread_exit(ret); 

而且別忘了free這個指針。

+2

現在你返回一個局部變量的__address__。而作者想要返回__value__。 –

+0

這很危險。 :)但我只是修復了警告信息。關注這個問題。但是,是的,我會編輯它以反映這一點。 – askmish

+0

好吧,這樣的修復以這種方式改變了行爲,它不再有用。 –

0

您正在投射非指針指向一個指針 - 這可能是您爲什麼得到警告。 也許你可以修改你的代碼來使用int*而不是你的int ret,並將其轉換爲void*

編輯:正如託尼獅子提到的。

3

所以,你試圖從一個線程函數返回一個整數值。一個POSIX線程函數只能返回void*

有幾種方法可以從另一個線程返回一個值:

1)您可以轉換爲void*和背部的整數,void*足夠寬而不截斷持有的價值:

void *Thrd(void *vdata) { 
    int value = ...; 
    void* thread_return_value = (void*)value; 
    return thread_return_value; 
} 
// ... 
void* status; 
pthread_join(txThread, &status); 
int value = (int)status; 

2)傳遞返回值給線程函數的地址,使線程功能設定值:

struct Data { int return_value; }; 

void *Thrd(void *vdata) { 
    // ... 
    int value = ...; 
    struct Data* data = vdata; 
    data->return_value = value; 
    return NULL; 
} 
// ... 
pthread_create(&Thread, NULL, Thrd, &data); 
pthread_join(txThread, NULL); 
int value = data->return_value; 

3)讓線程分配返回值。連接()的另一個線程需要讀取該值並將其解除分配:

void *Thrd(void *vdata) { 
    // ... 
    int* value = malloc(sizeof *value); 
    *value = ...; 
    return value; 
} 
// ... 
void* status; 
pthread_join(txThread, &status); 
int* value = status; 
// ... 
free(value);