我遇到的问题是showData()中的printf调试语句会给我毫无意义的数字。即:thread_id为-1781505888。
如果我在设置thread_id,startIndex和stopIndex的值后立即在createThreads()中插入printf语句,则这些值将正确打印。当我将threadData作为pthread_create的参数传递时,或者从showData()中的threadArg读取数据时,数据以某种方式被破坏。同样,可以将N和k的值假定为整数,而N / k的余数为0。感谢所有帮助。
编辑:同样,如果它提供任何额外的信息,则当我在同一输入上运行此命令时,每次运行都会得到不同的输出。有时是无意义的数字,有时所有值都显示为0,有时会出现故障。
void createThreads(int k){
struct threadData threadData;
int numThreads = k;
int i = 0;
int err = 0;
pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads));
for(i = 0;i<numThreads;i++){
struct threadData threadData;
threadData.thread_id = i;
threadData.startIndex = ((N/k)*i);
if(i == numThreads -1){
threadData.stopIndex = ((N/k)*(i+1))-1;
}
else{
threadData.stopIndex = ((N/k)*(i+1));
}
err = pthread_create(&threads[i], NULL, showData, (void *)&threadData);
if(err != 0){
printf("error creating thread\n");
}
}
}
void *showData(void *threadArg){
struct threadData *threadData;
threadData = (struct threadData *) threadArg;
printf("thread id : %d\n", threadData->thread_id);
printf("start: %d\n", threadData->startIndex);
printf("stop : %d\n", threadData->stopIndex);
}
最佳答案
threadData
对您的for循环来说是本地的...在每次迭代中它都超出范围,因此指向它的指针在您的showData()
例程中无效。您可以改为动态分配它,并在delete
的末尾showData
分配它。
您可能也想将threads
数据返回给createThreads
的调用者,因此它可以join
线程等待showData
“工作”的完成。
例:
...
for(i = 0; i < numThreads; ++i)
{
struct threadData* threadData = new struct threadData;
threadData->thread_id = i;
threadData->startIndex = ((N/k)*i);
if(i == numThreads -1){
threadData->stopIndex = ((N/k)*(i+1))-1;
}
else{
threadData->stopIndex = ((N/k)*(i+1));
}
err = pthread_create(&threads[i], NULL, showData, (void*)threadData);
if(err != 0){
printf("error creating thread\n");
exit(1); // probably not worth trying to continue...
}
return threads;
}
void *showData(void *threadArg){
struct threadData* threadData = (struct threadData*)threadArg;
printf("thread id : %d\n", threadData->thread_id);
printf("start: %d\n", threadData->startIndex);
printf("stop : %d\n", threadData->stopIndex);
delete threadData;
}