首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

多线程统计多个资料的单词数目

2013-04-09 
多线程统计多个文件的单词数目由标题我们就可以知道意思了,这里我只是将最后自己优化后的代码贴出来,其他

多线程统计多个文件的单词数目

由标题我们就可以知道意思了,这里我只是将最后自己优化后的代码贴出来,其他版本以及请从我的资源中下载:http://download.csdn.net/detail/chenqiai0/5233058


#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<stdbool.h>#define filenumbers 3//表示文件个数#define filenamenum 256//表示文件名最长为256int cal(char filename[256]);void *thread_function(void *arg);int wordcount=0;//三个文件总的单词数int count[3]={0,0,0};//三个文件单词数初始值都是0char filenames[filenumbers][filenamenum]={"file1","file2","file3"};pthread_mutex_t  fileMutex;//定义一个互斥变量int main(){int i=0;int flag;//用于判断操作是不是正确pthread_t thread[3];//int count1=0,count2=0,count3=0;/*互斥锁初始化*/flag=pthread_mutex_init(&fileMutex,NULL);if(flag!=0){perror("Mutex initalization failed!\n");return 1;}/*create pthread*/for(i=0;i<3;i++){flag=pthread_create(&thread[i],NULL,thread_function,(void*)&filenames[i]);if(flag!=0){perror("Thread creation failed!\n");return 1;}}//pthread_join(thread[0],(void**)&count1);//pthread_join(thread[1],(void**)&count2);//pthread_join(thread[2],(void**)&count3);for(i=0;i<3;i++){pthread_join(thread[i],(void**)&count[i]);}wordcount=count[0]+count[1]+count[2];printf("总的单词数:%d\n",wordcount);return 0;}int cal(char filename[256]){bool start;int count=0;//用于记录单词数char c;long int offset;FILE *fp;fp=fopen(filename,"r");if(fp==NULL){printf("open filed!\n");exit(EXIT_FAILURE);}fseek(fp,0,SEEK_SET);start=true;//start=0用于表示单词的开始,start=1表示没有while(feof(fp)==0)//feof(fp)==0 表示还没有到文件尾{fread(&c,1,1,fp);if(c==' '&&start==1){start=1;}else if(c!=' '&&start==1){start=0;count++;}else if(c==' '&&start==0){start=1;}}printf("%s",filename);printf("word count:%d\n",count);return count;}void *thread_function(void *arg){return (void*)cal((char*)arg);}
相信大家都更好的办法,请留言!

热点排行