[cpp]
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<stdbool.h>
#define filenumbers 3//表示文件個數
#define filenamenum 256//表示文件名最長為256
int cal(char filename[256]);
void *thread_function(void *arg);
int wordcount=0;//三個文件總的單詞數
int count[3]={0,0,0};//三個文件單詞數初始值都是0
char 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);
}