2013-03-04 60 views
3

我目前正在使用pthreads的項目。到目前爲止,該項目啓動用戶指定數量的線程,然後在每個線程上執行一些工作,然後關閉。每個線程都存儲在一個動態分配的內存數組中。我做到這一點使用:pthread返回值到數組

pthread_create(&(threads[i]), NULL, client_pipe_run, (void *) &param[i]); 

我下一步需要做的是存儲這些線程的返回值:

threads = malloc(number_of_threads * sizeof(pthread_t));

然後我在一個for循環創建每個線程。我的理解是,我需要傳遞pthread_join指針的地址,我希望返回值存儲在這裏。這是我有點困惑的地方。我很好地指出這一點,然後我的大腦有一個融化哈哈。這是我對如何達致這想法,但我不相信這是正確的:

int *return_vals = malloc(sizeof(int) * number_of_threads); 
for(i = 0; i< number_of_threads; i++) 
{ 
pthread_join(&(threads[i]),(void *) &(return_vals[i])); 
} 

然後得到的返回值,我會做類似的東西:

int val = *(return_val[0]); 

任何幫助的這將不勝感激!

+0

你結帳這篇文章:http://stackoverflow.com/questions/2251452/how-to-return-a-value-from-thread-in-c – zzk 2013-03-04 19:03:24

回答

5

請注意,您爲您的線程這樣的分配內存:

threads = malloc(number_of_thread * sizeof(pthread_t)); 

但對於返回值,你這樣做:

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

即線程的數量應該在數採取這裏太:

int *return_vals = malloc(number_of_thread * sizeof(int)); 

然後,您可以將返回值轉換爲void*

void *foo(void *arg) { 
    int i = 7; 
    return (void*)i; 
} 

int main(void) { 
    int i = 0; 
    int thread_count = 3; 
    pthread_t* threads = malloc(thread_count * sizeof(pthread_t)); 
    int *return_vals = malloc(thread_count * sizeof(int)); 

    // create threads: 
    for(i = 0; i < thread_count; ++i) 
     pthread_create(&threads[i], NULL, &foo, NULL); 

    // wait untill they finish their work: 
    for(i = 0; i < thread_count; ++i) 
     pthread_join(threads[i], (void**) &return_vals[i]); 

    // print results: 
    for(i = 0; i < thread_count; ++i) 
     printf("Thread %d returned: %d\n", i, return_vals[i]); 

    // clean up: 
    free(return_vals); 
    free(threads); 

    return 0; 
} 

,或者你可以確保你的代碼不作任何推定約你回來是小於或等於sizeof(void*)類型的大小和線程內動態分配的返回值內存:

void *foo(void *arg) { 
    int* ret = malloc(sizeof(int)); 
    *ret = 7; 
    return ret; 
} 

int main(void) { 
    int i = 0; 
    int thread_count = 3; 
    pthread_t* threads = malloc(thread_count * sizeof(pthread_t)); 

    // array of pointers to return values of type int: 
    int **return_vals = calloc(thread_count, sizeof(int*)); 

    // create threads: 
    for(i = 0; i < thread_count; ++i) 
     pthread_create(&threads[i], NULL, &foo, NULL); 

    // wait untill they finish their work: 
    for(i = 0; i < thread_count; ++i) 
     pthread_join(threads[i], (void**) &return_vals[i]); 

    // print results: 
    for(i = 0; i < thread_count; ++i) 
     printf("Thread %d returned: %d\n", i, *return_vals[i]); 

    // clean up: 
    for(i = 0; i < thread_count; ++i) 
     free(return_vals[i]); 
    free(return_vals); 
    free(threads); 

    return 0; 
} 

但是如果您選擇了後者,請注意您可能會遇到的內存泄漏。

+0

哎呀不能相信我離開了那>。 < 謝謝你的回答!我真的很感謝:) – 2013-03-04 19:31:13

+1

@ amura.cxg:另外請注意,你正在創建一個'int'數組:所以你應該傳遞給'malloc'' sizeof(int)* number_of_threads',而不是'sizeof(int *) * number_of_threads' – LihO 2013-03-04 19:38:07

+0

感謝您指出:) – 2013-03-04 20:22:51