【发布时间】:2012-05-11 10:39:12
【问题描述】:
我是 C 语言中的 pthreads 的新手,我正在编写一个简单的程序,可以在多个文件中并行查找单词。但是,每当我输入多个文件时,输出都会发生变化,这表明存在我没有在我的代码中修复的竞争条件。你能帮我修一下吗?
下面的sn-p在main中,制作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;
}
为了澄清,问题是我在连续运行程序时得到不同的结果。一个电话 $程序名 文件1 文件2 打印与之后调用的相同调用不同的结果。但是请注意,当只传递一个文件时,该程序可以工作。
感谢任何帮助。
【问题讨论】:
-
输出如何变化?来自同一文件或混合输出的不同结果?
-
@hmjd 是的,输出不同。例如:
$ ./a.out blu bla输出File blu has 0 occurences of the word PlutoFile bla has 5 occurences of the word Pluto和$ ./a.out blu bla之后的相同命令输出File bla has 1 occurences of the word PlutoFile blu has 4 occurences of the word Pluto -
无需投射到
void*或从void* -
@JensGustedt 演员阵容不应该真正影响输出
-
重复运行
$ ./a.out blu,是否得到一致的结果?你能发布ffindWord()函数定义吗?还有你用来构建的编译器命令。
标签: c pthreads race-condition file-pointer