【问题标题】:pthread start routine returning an array of intspthread 启动例程返回一个整数数组
【发布时间】:2013-11-28 23:46:27
【问题描述】:

我不熟悉从 pthread 启动例程返回内容,所以我来 SO 寻求帮助。

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

如果有不同的方法来实现这一点,我很想听听!

这是我得到的:

//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]);
}      

【问题讨论】:

  • 在线程中分配素数数组并将其作为成员添加到您的Data 中,您可能也需要计数/大小等。此外,如果您使用多个线程,请注意谁的数据是谁的。另外,记得释放父线程中的数据。
  • 该代码将返回位于堆栈中的数组的地址。一旦返回调用代码,该数组将不存在。

标签: c pthreads


【解决方案1】:

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

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 结构中的结果分配一个数组,然后将其填充到那里。

【讨论】:

    猜你喜欢
    • 2019-03-03
    • 2016-07-10
    • 2023-03-03
    • 2017-12-04
    • 1970-01-01
    • 2014-10-31
    • 2011-05-27
    • 2014-06-28
    • 2015-05-31
    相关资源
    最近更新 更多