我正在解决这个问题:从命令行中提取一个字母和相同文件的名称,计算字符在每个文件中的出现次数,每个文件使用一个线程,然后打印总的出现次数。
这是我的代码:
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发布于 2017-10-06 11:58:24
这里有几个线程问题。
1)主线程将异步继续到新产生的线程。给定这些代码,主线程很可能会在CountFile线程完成之前完成并退出。在Linux上,当主线程返回时,C运行时将执行一个exit_group系统调用,该系统调用将终止所有线程。
您需要添加一些检查,以确保CountFile线程已经完成了相关部分的工作。在本例中,请看一下在主线程中使用pthread_join()。
2)主线程中的'cf‘存储是一个堆栈局部变量,它通过指针传递给每个线程。但是,由于它是相同的存储,因此可能会发生几种类型的故障。a)当工作线程正在访问工作单元时,可以由主线程更新工作单元。b)将同一工作单元发送到多个/所有线程。
你可以用几种方法来解决这个问题:“cf”可以是每个线程的CharFile数组。或者'cf‘可以动态地分配给每个线程。前者的性能和内存效率更高,但后者在结构上可能更好。具体地说,主线程将其本地堆栈空间中的地址分配给另一个线程。
3)一旦对项目#1进行了寻址,并且线程在主线程printf之前退出,互斥锁的使用就可以了。但不管怎样,将pthread_mutex_locks放在'sum‘的主线程访问周围可能会更好。对于这段代码,这可能不是必需的,但未来的代码重构可能会改变这一点。
https://stackoverflow.com/questions/46576148
复制相似问题