多線程統計多個檔案的單詞數目

來源:互聯網
上載者:User

由標題我們就可以知道意思了,這裡我只是將最後自己最佳化後的代碼貼出來,其他版本以及請從我的資源中下載: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);}
相信大家都更好的辦法,請留言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.