多线程 - 比单线程慢

multithreading - slower than single threading

当我 运行 我的程序使用多线程而不是单线程时它变得更慢,难道它不应该更快吗?该程序应该遍历从起始目录开始的所有目录,并查找并打印所有名为 X 的文件。代码如下:

while(!done) {
        pthread_mutex_lock(&lock);
        if(!list_isEmpty(dirList)) {
            DIR *dir;
            struct dirent *d;
            char *folder;

            folder = strdup(list_inspect(1, dirList));
            list_remove(list_inspect(1,dirList), dirList);
            if(folder == NULL) {
                perror("failed strdup on path\n");
                pthread_mutex_unlock(&lock);
                continue;
            }
            pthread_mutex_unlock(&lock);
            dir = opendir(folder);
            if(dir == NULL) {
                perror(folder);
                free(folder);
                continue;
            }
            while ((d = readdir(dir)) != NULL) {
                if(strcmp(d->d_name, ".")==0 || strcmp(d->d_name, "..")==0) {
                    continue;
                }
                searchBasedOnType(folder, info, d);
            }
            closedir(dir);
            free(folder);
        }
        else {
            if(sleepCounter == info->nrthr-1) {
                done = true;
                pthread_cond_broadcast(&cond);
                pthread_mutex_unlock(&lock);
                break;
            }
            else {
                sleepCounter++;
                pthread_cond_wait(&cond, &lock);
                sleepCounter--;
                pthread_mutex_unlock(&lock);                
            }
        }   
    }

这里还有一个函数 searchBasedOnTypes 调用函数与互斥锁等的例子:

char currentPath[FILENAME_MAX];
        struct stat buf;

        strcpy(currentPath,f);
        if(currentPath[strlen(currentPath)-1] != '/') {
            strcat(currentPath, "/");
        }
        strcat(currentPath, d->d_name);
        if(lstat(currentPath, &buf) == -1){
          perror(currentPath);
          return;
        }

        if(S_ISDIR(buf.st_mode)) {
            pthread_mutex_lock(&lock);
            char *newDir = malloc(sizeof(currentPath));
            if(newDir == NULL) {
                perror("Failed allocating memory for path\n");
                pthread_mutex_unlock(&lock);
                return;
            }
            strcpy(newDir, currentPath);
            printf("insert %s\n", newDir);
            list_insert(newDir, dirList);
            printf("done\n");
            pthread_cond_signal(&cond);
            pthread_mutex_unlock(&lock);
        }
        if(strcmp(name,d->d_name) == 0) {
            printf("%s\n",currentPath);
        }

谁能帮我找出在 运行 多线程时可能会降低程序速度的原因,也许还有解决方案?感谢您提前提供的所有帮助和建议!

人们通常认为线程是培根的计算等价物(让一切变得更好)。

现实中:多线程并不总能加快速度。如果您的线程正在访问可以并行服务的不同硬件资源,则多线程通常只会加快速度。不共享内存(或很少共享内存)的两个不同内核上的两个线程 运行 CPU 绑定任务可能会更快。如果他们共享内存或访问同一个磁盘,他们很有可能会竞争。

由于磁盘是迄今为止您的程序正在处理的最慢的资源,所以您没有看到任何加速,我一点也不感到惊讶。使用多个磁盘(每个磁盘一个线程)尝试相同的实验,您可能会看到改进。

此外,您的程序具有的同步(互斥锁)越多,您通常拥有的并行度就越低。因此,性能将进一步下降。