gpt4 book ai didi

c - pthread 启动例程返回一个整数数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:06:20 24 4
gpt4 key购买 nike

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

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

如果有其他方法可以完成此任务,我很乐意听到!

这是我得到的:

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

最佳答案

你返回的指针在线程函数中不能指向一个自动保存期限的数组,因为一旦线程函数返回,它就会被销毁。不过,您可以使用动态分配。 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 结构中的结果分配一个数组,并让它填充到那里。

关于c - pthread 启动例程返回一个整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20276334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com