我是新來的C線程中的pthreads,我正在寫一個簡單的程序,它可以並行地在多個文件中查找單詞。但是,只要我輸入多個文件,輸出就會變化,這表明我的代碼中沒有修復競爭條件。你能幫我解決嗎?C中的pthreads的競態條件
下面的代碼片段是主要的,使pthreads。
int i = 0;
char *word = "Pluto"; //Word to be found
Message messages[argc-1];
pthread_t threads[argc-1];
for(i; i < argc - 1; i++){
messages[i].file = argv[i + 1];
messages[i].word = word;
messages[i].fp = fopen(argv[i + 1], "r");
int iret = pthread_create(&threads[i], NULL, threadFindWord, (void*) &(messages[i]));
}for(i = 0; i < argc - 1; i++){
pthread_join(threads[i],NULL);
}
每個線程調用該函數:
Message *msg;
msg = (Message *) ptr;
int numFound = ffindWord(msg->fp, msg->word);
printf("File %s has %i occurences of the word %s\n", msg->file, numFound, msg->word);
fclose(msg->fp);
pthread_exit(NULL);
下面是在文件中查找單詞的代碼)
int findWord(char * file, char * word){
char * current = strtok(file, " ,.\n");
int sum = 0;
while (current != NULL){
//printf("%s\n", current);
if(strcmp(current, word) == 0)
sum+=1;
current = strtok(NULL, " ,.\n");
}
return sum;
}
int ffindWord(FILE *fp, char *word){
fseek(fp, 0, SEEK_END);
long pos = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *bytes = malloc(pos);
fread(bytes, pos, 1, fp);
bytes[pos-1] = '\0';
int sum = findWord(bytes, word);
free(bytes);
return sum;
}
爲了澄清,問題是,我得到連續運行程序時會產生不同的結果。呼叫 $ programname file1 file2 打印與剛剛調用的同一個呼叫不同的結果。但請注意,只有一個文件通過時,程序才能工作。
任何幫助表示讚賞。
輸出如何變化?來自同一文件或混合輸出的不同結果? – hmjd
@hmjd是的輸出變化。例如:'$ ./a。out blu bla'輸出文件藍色文件有0個出現在Pluto文件中的文件bla有5個出現在Pluto這個文件後面和在$ $ /a.out blu bla'輸出文件後面有相同的命令File bla有1次出現的冥王星文件# '文件藍光有4個詞冥王星' – pretobomba
沒有必要投到或退出'void *' –