pthread返回值到数组

时间:2013-03-04 18:58:49

标签: c pthreads pthread-join

我目前正在开发一个使用pthreads的项目。到目前为止,该项目启动了用户指定的线程数,并在每个线程上执行一些工作然后关闭。每个线程都存储在动态分配的内存数组中。我是这样做的:

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

然后我在for循环中创建每个线程:

pthread_create(&(threads[i]), NULL, client_pipe_run, (void *) &param[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]);

对此有任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:6)

请注意,您正在为线程分配内存,如下所示:

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*),并在线程内动态地为返回值分配内存: / p>

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;
}

但是如果您选择后者,请注意可能最终导致的内存泄漏。