【发布时间】: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中,您可能也需要计数/大小等。此外,如果您使用多个线程,请注意谁的数据是谁的。另外,记得释放父线程中的数据。 -
该代码将返回位于堆栈中的数组的地址。一旦返回调用代码,该数组将不存在。