繁体   English   中英

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

[英]pthread start routine returning an array of ints

我不熟悉从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]);
}      

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

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

然后在main函数中:

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结构中为结果分配一个数组,并将其填入其中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM