2016-10-02 112 views
0

我用pthread_join函數在昨天遇到了問題,它出現complie錯誤,我在網上搜索很久,但沒有解決它。爲什麼不能用**來得到pthread_join的返回值

pthread_join.c 

#include <stdio.h> 

#include <pthread.h> 

void* say_hello(void* args) 
{ 

    printf("hello from thread\n"); 
    pthread_exit((void*)1); 
} 

int main() 
{ 

    pthread_t tid; 
    int iRet=pthread_create(&tid,NULL,say_hello,NULL); 
    if(iRet) 
    { 
      printf("pthread create error:iRet=%n\n",iRet); 
      return iRet; 
    } 

    void *retval; 
    iRet=pthread_join(tid,&retval); 
    if(iRet) 
    { 
      printf("pthread_join error:iRet=%d\n",iRet); 
      return iRet; 
    } 


     printf("retval=%ld\n",(long)**(&retval)); 
     // printf("retval=%ld\n",(long)retval); 
     return 0; 

}

$ error:invalid use of void expression 

我嘗試使用(&retval)獲得的pthread_join返回值。我覺得retval屬於void **,那麼我使用(retval)應該可以得到值,但是失敗了。我不能用void來獲取**指針的值,我估計retval是值通過pthread_join,但如果使用** retval來獲取它,不能成功。

我用gcc編譯它,它會顯示:

$ error:invalid use of void expression  
+0

使用'的printf( 「RETVAL =%LD \ n」,(長)RETVAL));'或'的printf(「RETVAL =%d \ n「,(int)retval));' – alk

回答

2

爲什麼不能用**來獲得在pthread_join

void *retval; 
... 
printf("retval=%ld\n",(long)**(&retval)); 
的返回值

retvalvoid*&retvalvoid**,所以**(&retval)void。然後,您正試圖將void投射到long,這是不可能的。這就是你從gcc獲得的原因:error:invalid use of void expression

一個posix線程啓動例程必須返回一個void*類型的值。在say_hello()中,根據需要返回int(1)正確鑄造到void*

pthread_join(pthread_t thread, void **value_ptr)要求作爲第二個參數的地址爲void*以存儲連接線程的返回值。通過撥打pthread_join(tid,&retval),您可以正確地向pthread_join()提供retval的地址,即void*。這樣做,線程返回值(void*)1被存儲到retval中。現在

,如果你要打印的返回值retval,澆鑄爲long,正確的語法是你註釋掉一個:

printf("retval=%ld\n",(long)retval); 

你還可以這樣寫這個如下:

printf("retval=%ld\n",(long)*(&retval)); 

這相當於雖然不會使很多意義......

+0

它爲什麼可以使用void *存儲返回值,void *是pterter,它是一個地址,地址可以存儲值嗎?我不明白。 – Marcos

+0

@Marcos:'void *'通常表示一個內存地址,但不一定;在'say_hello()'函數中,你將一個'int'(1)轉換成了一個'void *',這意味着你使用了一個'void *'來存儲一個'int'值,因此它不代表有效的內存地址。所以是的,一個指針可以存儲一個不是地址的值。 – shrike

相關問題