2014-01-24 41 views
20

我正在學習P線程的整數。我的代碼以我想要的方式執行,我可以使用它。但它給我一個編譯警告。警告:投往/返指針從/到不同大小

我編譯使用:

gcc test.c -o test -pthread 

與GCC 4.8.1。我得到警告

test.c: In function ‘main’: 
test.c:39:46: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] 
    pthread_create(&(tid[i]), &attr, runner, (void *) i); 
              ^
test.c: In function ‘runner’: 
test.c:54:22: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] 
    int threadnumber = (int) param; 
        ^

這個錯誤出現以下代碼:

#include <pthread.h> 
#include <stdlib.h> 
#include <stdio.h> 

#define MAX_THREADS 10 

int sum; /* this data is shared by the thread(s) */ 
void *runner(void * param); 

int main(int argc, char *argv[]) 
{ 
    int num_threads, i; 
    pthread_t tid[MAX_THREADS];  /* the thread identifiers */ 
    pthread_attr_t attr; /* set of thread attributes */ 

    if (argc != 2) { 
    fprintf(stderr, "usage: test <integer value>\n"); 
    exit(EXIT_FAILURE); 
    } 

    if (atoi(argv[1]) <= 0) { 
    fprintf(stderr,"%d must be > 0\n", atoi(argv[1])); 
    exit(EXIT_FAILURE); 
    } 

    if (atoi(argv[1]) > MAX_THREADS) { 
    fprintf(stderr,"%d must be <= %d\n", atoi(argv[1]), MAX_THREADS); 
    exit(EXIT_FAILURE); 
    } 

    num_threads = atoi(argv[1]); 
    printf("The number of threads is %d\n", num_threads); 

    /* get the default attributes */ 
    pthread_attr_init(&attr); 

    /* create the threads */ 
    for (i=0; i<num_threads; i++) { 
    pthread_create(&(tid[i]), &attr, runner, (void *) i); 
    printf("Creating thread number %d, tid=%lu \n", i, tid[i]); 
    } 

    /* now wait for the threads to exit */ 
    for (i=0; i<num_threads; i++) { 
    pthread_join(tid[i],NULL); 
    } 
    return 0; 
} 

/* The thread will begin control in this function */ 
void *runner(void * param) 
{ 
    int i; 
    int threadnumber = (int) param; 
    for (i=0; i<1000; i++) printf("Thread number=%d, i=%d\n", threadnumber, i); 
    pthread_exit(0); 
} 

我怎樣才能解決這個警告呢?

回答

34

快速哈克修復可能只是投給long而不是int。在很多系統上,sizeof(long) == sizeof(void *)

一個更好的想法可能是使用intptr_t

int threadnumber = (intptr_t) param; 

pthread_create(&(tid[i]), &attr, runner, (void *)(intptr_t)i); 
+0

或鑄造成'長long'在64位機器/編譯器。 – thejinx0r

+0

@ thejinx0r肯定,但它仍然是,你不能依靠'的​​sizeof(加長)的意義==的sizeof(void *的)'黑客攻擊。 – tangrs

+0

或將其轉換爲適合我的'size_t'。 –

1
pthread_create(&(tid[i]), &attr, runner, (void *) i); 

您正在傳遞局部變量i作爲runnersizeof(void*) == 8sizeof(int) == 4(64位)的參數。

如果你想通過i,你應該把它包裝成一個指針或東西:

void *runner(void * param) { 
    int id = *((int*)param); 
    delete param; 
} 

int tid = new int; *tid = i; 
pthread_create(&(tid[i]), &attr, runner, tid); 

你可能只是想i,在這種情況下,以下應該是安全的(但遠非推薦) :

void *runner(void * param) { 
    int id = (int)param; 
} 

pthread_create(&(tid[i]), &attr, runner, (void*)(unsigned long long)(i)); 
0

我也得到同樣的警告。所以爲了解決我的警告,我把int轉換爲long,然後這個警告消失了。而關於「由大小不同的整數轉換爲指針」的警告,你可以離開這個警告,因爲指針可以容納任何變量的值,因爲指針在64倍是64位,並且在32倍是32位的。