gpt4 book ai didi

c++问题将信息传递给pthreads

转载 作者:行者123 更新时间:2023-11-28 02:30:49 30 4
gpt4 key购买 nike

我遇到的问题是 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;
}

关于c++问题将信息传递给pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29067946/

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