我正在處理此問題:從命令行獲取一個字母和相同文件的名稱,計算每個文件中char的出現次數,每個文件使用一個線程,以及打印出現的總次數。使用線程和互斥對文件計數char
這是我的代碼:
typedef struct _CharFile{
char c;
char *fileName;
} CharFile;
pthread_mutex_t count = PTHREAD_MUTEX_INITIALIZER;
int sum = 0;
void *CountFile(void *threadarg);
int main(int argc, const char * argv[]) {
pthread_t threads[argc-2];
int chck, t;
CharFile cf;
for (t=0 ; t<argc-2 ; t++){
cf.c = argv[1][0];
cf.fileName = (char *)argv[t + 2];
chck = pthread_create(&threads[t], NULL, CountFile, (void *) &cf);
if (chck){
printf("ERROR; return code from pthread_create() is %d\n", chck);
exit(-1);
}
}
printf("%lld occurrences of the letter %c in %lld threads\n", (long long)sum, argv[1][0], (long long)argc-2);
return 0;
}
void *CountFile(void *threadarg){
FILE *in;
CharFile *cf;
char c;
int counter = 0;
cf = (CharFile *) threadarg;
in = fopen(cf->fileName, "r");
if (in == NULL){
perror("Error opening the file!\n");
pthread_exit(NULL);
}
while (fscanf(in, "%c", &c) != EOF){
if(c == cf->c){
counter += 1;
}
}
fclose(in);
pthread_mutex_lock(&count);
sum += counter;
pthread_mutex_unlock(&count);
pthread_exit(NULL);
}
我沒有得到任何錯誤的文件打開或線程創建的,但我的輸出總是0作爲總的發生。我也嘗試在線程中打印counter
,並且我在每個線程中都得到了相同的數字,即使我的輸入文件不同。我錯誤地使用互斥鎖還是存在其他錯誤?
這是我的輸出中的一個:
61 occurrences of e in this thread
0 occurrences of the letter e in 3 threads
61 occurrences of e in this thread
61 occurrences of e in this thread
Program ended with exit code: 9
您不必等待您的線程完成。 –
我該怎麼做? –
但是你想要。通常最糟糕的方式是使用'pthread_join'。但這很簡單,你應該首先學習。 –