请注意,您正在为线程分配内存,如下所示:
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;
}
但是,如果您选择了后者,请注意最终可能导致的内存泄漏。