我目前正在从事一个使用 pthreads 的项目。到目前为止,该项目启动了用户指定数量的线程,并在每个线程上做了一些工作,然后关闭。每个线程都存储在一个动态分配的内存数组中。我这样做使用:
threads = malloc(number_of_threads * sizeof(pthread_t));
然后我在 for 循环中创建每个线程:
pthread_create(&(threads[i]), NULL, client_pipe_run, (void *) ¶m[i]);
我接下来需要做的是存储这些线程的返回值。我的理解是我需要将要存储返回值的指针的地址传递给 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]);
如有任何帮助,我们将不胜感激!
最佳答案
请注意,您正在为这样的线程分配内存:
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;
}
但如果您选择了后者,请注意可能导致的内存泄漏。
关于c - pthread 将值返回到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208997/