【问题标题】:Debug recursive thread call in C在 C 中调试递归线程调用
【发布时间】:2009-11-17 01:44:30
【问题描述】:

在过去一天半的空闲时间里,我一直在尝试调试我的代码,但我不知道我的代码有什么问题。当我将 close() 函数添加到递归调用时,程序给了我一个无效的指针。但是当我删除 close() 函数调用时,程序运行良好,除了它没有做它应该做的事情,即:

  • 将用户中的所有文件大小相加 输入目录
  • 打开子目录(如果有)并添加 把里面的所有文件 子目录

相反,它将输入目录中的所有文件大小相加,并能够打开最后一个子目录并将该目录中的文件添加到总文件大小计数中。

我正在尝试用线程来做到这一点。 main() 函数从用户输入目录创建一个主线程并立即运行opendirectory()

/*
 * Iterates through given directory
 */
void *opendirectory(void *t)
{
 pthread_mutex_lock(&dirlock);
 DIR *dpntr;
 struct dirent *dentry;
 char new_directory[512], dir = t;

 printf("OPENING DIRECTORY ... %s\n", t);

 /* Checks if given directory can be opened */
 if((dpntr = opendir(t)) == NULL) {
  printf("DIRECTORY FAILED ...%s\n",t);
  perror("ERROR -- COULD NOT OPEN DIR");
  pthread_exit(NULL);
 }

 printf("DIRECTORY OPENED: %s\n", t);

 /* Read each file in current directory */
 while ((dentry = readdir(dpntr)) != NULL ) {
  /* Ignore special directories */
  if(strcmp(dentry -> d_name, ".") == 0 || strcmp(dentry -> d_name, "..") == 0) {
   continue;
  } else {
   compilelist( t, dentry->d_name );
  }
 }

 pthread_mutex_unlock(&dirlock);
 /* Checks if directory can be closed */
 if(closedir(dpntr) < 0)
  printf("ERROR CLOSING %s.\n", t);

}

该函数将确定是否应创建新线程并应递归运行。

/*
 * Determines if current file is a directory
 * Creates a new thread if true
 */
void compilelist (const char* dirname, const char *filename)
{
    pthread_mutex_lock(&filelock);
    struct stat statdata;
    char *filepathname, *dpntr;

    /* Allocate memory for filepathname */
    if((filepathname = (char *) malloc(sizeof(char) * strlen(dirname))) == NULL)
    {
        printf("CANNOT ALLOCATE MEMORY FOR FILE PATH NAME.");
        pthread_exit(NULL);
    }

    /* Concats directory name with file name */
    if(dirname[strlen(dirname) -1] == '/')
    {
        pthread_mutex_lock(&pathlock);
        sprintf(filepathname, "%s%s", dirname, filename);
        pthread_mutex_unlock(&pathlock);
    }else
    {
        pthread_mutex_lock(&pathlock);
        sprintf(filepathname, "%s/%s", dirname, filename);
        pthread_mutex_unlock(&pathlock);
    }

    lstat(filepathname, &statdata);

    /* Calls print_statdata() if current item is a file */
    if(!(S_ISDIR(statdata.st_mode)))
    {
        printf("FILE: %s\n", filepathname);
        if(!stat( filepathname, &statdata))
        {
            print_statdata( filename, &statdata );
        }
        else {
            fprintf (stderr, "GETTING STAT FOR %s", filepathname);
            perror( "ERROR IN STATDATA WHILE GETTING STAT");
        }
    }
    /* Recursive call to opendirectory() */
    else {
        pthread_mutex_lock(&dircountlock);
        dirCount++;
        pthread_mutex_unlock(&dircountlock);
        dpntr = filepathname;
        free(filepathname);
        printf("SUB-DIRECTORY THREAD: %s\nTHREAD ID NUMBER: %d\n", dpntr, dirCount);
        pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
        pthread_create(&threads[dirCount-1], &attr, opendirectory, (void *)dpntr);
    }

    pthread_mutex_unlock(&filelock);

}

这里是main()

/*
 * Main function prompts user for a directory
 */
int main(int argc, char *argv[])
{
    int i;
    char *dPtr;
    // pthread_attr_t attr;

    printf("ENTER A DIRECTORY:\n\t");
    scanf("%s", directory);
    dPtr = directory;

    /* Initialize mutex and condition variable objects */
    pthread_mutex_init(&mutex, NULL);
    pthread_mutex_init(&filelock, NULL);
    pthread_mutex_init(&dirlock, NULL);
    pthread_mutex_init(&dircountlock, NULL);
    pthread_cond_init (&count_threshold_cv, NULL);

    /* For portability, explicitly create threads in a joinable state */
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    pthread_create(&threads[0], &attr, opendirectory, (void *)dPtr);

    /* Wait for all threads to complete */
    for (i = 0; i < dirCount; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("TOTAL DIRECTORY SIZE: %d\n", dirSize);

    /* Clean up and exit */
    pthread_attr_destroy(&attr);
    pthread_mutex_destroy(&mutex);
    pthread_mutex_destroy(&filelock);
    pthread_mutex_destroy(&dirlock);
    pthread_mutex_destroy(&dircountlock);
    pthread_cond_destroy(&count_threshold_cv);
    pthread_exit (NULL);

}

还有全局变量...

pthread_mutex_t mutex;
pthread_mutex_t dirlock;
pthread_mutex_t filelock;
pthread_mutex_t dircountlock;
pthread_mutex_t threadlock;
pthread_cond_t count_threshold_cv;
pthread_attr_t attr;
pthread_t threads[128]; // handles up to 128 threads (i.e. 128 directories, change accordingly)
char directory[512];
int dirSize = 0;
int dirCount = 1; // user's input directory

感觉compilelist()函数底部调用的pthread_create()不能正常工作。 threads[] 指的是默认大小为 20 的全局线程数组,假设总目录不超过 20 个。由于用户的输入目录,dirCount 从 1 开始,并随着遇到新目录而增加。

【问题讨论】:

  • 如果您想获得这方面的帮助,您必须提供整个源代码(dPtr 声明在哪里?dir = t 是错误的,等等...)
  • 您可以将代码发布到 main() 吗?或者至少你在哪里设置线程属性/处理加入/等?
  • 我会稍微编辑一下我的帖子,但是当我在考虑一种使其递归的方法时,我将我的大部分变量设为全局......可能是一个非常新手的错误,但任何指针都会很棒!我正在将一些指针从全局更改为本地。

标签: c multithreading directory


【解决方案1】:

您的代码:

dpntr = opendir(t)

...

if(closedir(t) < 0)

应该是:

if(closedir(dpntr) < 0)

【讨论】:

  • 哦......谢谢......这是一个我严重忽略的简单错误,应该三重检查!
  • 我已经更改了它,但是当我在笔记本电脑上运行程序时仍然遇到分段错误。目前似乎无法通过 ssh'ing 连接到 Linux 系统进行测试...
【解决方案2】:

在这里我发现你的代码有两个问题:

  1. 正如 wrang-wrang 所提到的,closedir(t) 会导致段错误。

  2. "char 文件路径名[512];" compilelist() 是一个本地内存缓冲区,但是你将它传递给你的线程(opendirectory)并连续使用它。您应该改用复制或动态分配。

Effo 更新@2009nov17: 修复以上 2 点后,到目前为止它在我的 FC9 x86_64 上运行良好。顺便说一句:线程数 20 确实不够。

【讨论】:

  • 现在将为 closedir() 编辑帖子,忘记在上次编辑时更新。我一定会检查 char 文件路径名 [512] 的用法并考虑如何去做。谢谢。
  • 好的,所以我相信我已经正确设置它以使用动态分配,但我仍然在未打开子目录的线程上遇到错误。稍后我会发布我的新代码。
  • 我不应该释放(文件路径名)吗?我想我必须这样做才能正确地 malloc 进行递归调用......
  • 1.在线程 opendirectory() 中释放它。 2. 如果第 1 点,那么在 main 中也做动态分配。 3.不要忘记在其他分支上释放它例如!ISDIR()和opendir()失败等等。
  • Hrm ...也许只是我,但是当我不释放(文件路径名)时它似乎可以工作,并且在我的情况下它在较小的目录上工作正常...感谢您的帮助!
【解决方案3】:

第一个问题:

过去一天半的空闲时间

不要那样做,你的大脑不是为此而生的。分配一个时间,告诉你的同事/妻子和孩子,如果他们在这段时间打扰你,就会有枪声和警察介入:-)

其他问题:不知道(因此是社区 wiki)。

【讨论】:

  • 有一点需要注意,@Kenji(我认为这不是您的特定问题)。粗略一瞥,我看不到任何阻止主线程在您的子线程有机会使用它之前更改文件路径名的东西(通过 dPtr 指针)。
  • 我想你可能正在做一些事情,我正在尝试将一些全局变量切换到本地并重新编译...
  • @Kenji,在这种情况下,我倾向于使用受互斥体保护的标志变量。主线程在创建子线程之前将其设置为 1,然后循环直到为 0。子线程将相关数据(数据,而不是指向数据的指针)复制到本地存储,然后将其设置为 0 并继续。这保证了每个线程不会踩到另一个线程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 1970-01-01
  • 2016-08-07
相关资源
最近更新 更多