pthread启动例程返回一个int数组

时间:2013-11-28 23:46:27

标签: c pthreads

我不熟悉从pthread启动程序中返回的东西,所以我来到SO寻求帮助。

启动例程将计算给定范围的一些素数,将它们存储在一个int数组中,然后将该数组返回到将要打印的主数据。

如果有不同的方法来实现这一点,我很乐意听到它!

这就是我所拥有的:

//start routine
void *threadCreate(void* arg){
    int threadNumber = threadCount;
    threadCount++;
    Data *data;
    data = (struct Data*)arg;
    int primes[data->end]; //I don't know how many primes we will have, but I think if I use the end range value as a size it will be more than enough.
    int k = 0; //Index of the int array
    printf("Thread #%d results: ", threadNumber);
    for (int i = data->start; i <= data->end; i++){
        if (isPrime(i)){
            printf("%d ", i);
            primes[k] = i;
            k++;
        }
    }
    printf("\n");
    pthread_exit((void*)primes);
}

//in main, this is where we print our array
//I don't know the correct way to get this array
void *retval;

pthread_join(tid, &retval);

//im aware the next part is more than likely incorrect, I am just trying to illustrate what I am trying to do

for (int i = 0; i < len((int [])retval); i++){
   printf("%d ", (int[])retval[i]);
}      

1 个答案:

答案 0 :(得分:3)

您返回的指针不能是线程函数中具有自动存储持续时间的数组,因为一旦线程函数返回它将被销毁。但是,您可以使用动态分配。主函数还需要知道返回数组中有多少个数字 - 最简单的方法是使用零作为标记,因为零的素数是未定义的。

int *primes = malloc((data->end + 1) * sizeof primes[0]);

if (primes)
{
    int k = 0; //Index of the int array

    for (int i = data->start; i <= data->end; i++)
    {
        if (isPrime(i))
        {
            printf("%d ", i);
            primes[k] = i;
            k++;
        }
    }

    primes[k] = 0; /* Add sentinel to mark the end */
}

pthread_exit(primes);

然后在主要功能中:

void *retval;
int *primes;

pthread_join(tid, &retval);
primes = retval;

if (primes != NULL)
{
    for (int i = 0; primes[i] != 0; i++)
    {
       printf("%d ", primes[i]);
    }
}
else
{
    /* Thread failed to allocate memory for the result */
}

free(primes);

您也可以在传递给线程函数的Data结构中为结果分配一个数组,并将其填入其中。