当我使用多线程而不是单线程运行我的程序时,速度变慢了,这难道不应该更快吗?这个程序应该从一个起始目录开始遍历所有目录,并查找并打印所有名为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);
}
有人能帮我找出在多线程运行时可能会减缓程序速度的原因以及解决方案吗?非常感谢您提前给予的所有帮助和建议!