[英]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綁定任務的兩個線程可能會更快。 如果他們共享內存或者擊中相同的磁盤,那么他們很有可能會競爭。
由於磁盤是目前程序正在處理的最慢的資源,所以我並不感到驚訝你沒有看到任何加速。 嘗試使用多個磁盤(每個磁盤一個線程)進行相同的實驗,您可能會看到一個改進。
此外,您的程序具有更多同步(互斥鎖定),您通常具有的並行性越低。 因此,性能將進一步受損。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.