gpt4 book ai didi

c - 加入线程困惑

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

我正在做我的作业,我必须完成的是计算给定目录的目录和文件,但是我发现的每个目录也应该与我的进程的另一个线程一起计算,这就是我到目前为止所拥有的:

void *dirCounter(void *param){
queue<pthread_t> queue;
dir_ptr dir = (dir_ptr)param;
dir->countDir = 0;
DIR* dirName = dir->name;
struct dirent *curr;
off_t dsp;
dsp= telldir(dirName);
while(dsp!= -1){
curr = readdir(dirName);
if(curr == NULL){
break;
}
if(!strcmp(curr->d_name,".")|!strcmp(curr->d_name,"..")) { //To avoid counting . and ..
dsp = telldir(dirName); //Actual position asociated to the stream
continue; //Executes the beginning of the while
}
if(curr->d_type == DT_DIR){
dir->countDir++; //counts directories in the first level
//For each directory found, create another thread and add it to the queue:

pthread_attr_t attr1;
pthread_t tid1;
pthread_attr_init(&attr1);
dir_ptr par1 = (dir_ptr)malloc(sizeof(directorio));
par1->name = opendir(curr->d_name);
par1->countDir = par1->countFile = 0;
pthread_create(&tid1,&attr1, dirCounter, par1);
//queue.push(tid1);
}
if(curr->d_type == DT_REG){
dir->countFile++; //Counts files
}
dsp = telldir(dirName);
}
//pthread_join(tid1, NULL);
//while(!queue.empty()){
//pthread_join(queue.front(), NULL);
// queue.pop();
//}
printf("Dirs: %d Files: %d\n", dir->countDir, dir->countFile);
pthread_exit(NULL);
}

到目前为止,如果连接被注释,代码会计算“第一级”的当前文件和目录,然后它只会给出一个段错误,如果该行未被注释,它只会给出一个输出行,然后死掉段错误。我的想法是每当我找到一个目录时就创建一个线程,然后在最后加入所有这些线程以创建一个半递归例程。

修改:

char str[256];
strcpy(str, "./");
strcat(str, curr->d_name);
//strcat(str, "\"");
puts(str);
par1->name = opendir(str);
par1->countDir = par1->countFile = 0;
pthread_create(&tid1,&attr1, dirCounter, par1);
queue.push(tid1);

修改后的作用:打印所有目录,但是它确实会出现段错误并且某些线程无法完成它的任务。

最佳答案

问题的最直接原因是 dir->name 在创建的附加线程中为 NULL,因为 opendir(curr->d_name); 失败。这是因为目录 curr->d_name 不是绝对路径名 - opendir() 将在当前工作目录中查找您的目录正在尝试打开,但该目录实际上在您当前正在处理的目录中。

我建议不要将 DIR * 值传递给线程,而是简单地传递目录的路径名,并让线程执行 opendir()本身。然后它应该测试返回值,并且仅在 opendir() 返回非 NULL 时才继续调用 readdir()

当您找到一个目录条目时,您需要通过连接"/"curr->d_name 构造一个路径名以传递给新线程到正在处理的目录的路径名上。

请注意,您根本不需要 dsp 变量和对 telldir() 的调用。如果你有一个有效的 DIR *dir,你可以简单地循环它:

while (curr = readdir(dir)) {
/* Do something with curr */
}

关于c - 加入线程困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9799371/

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