By the title we can know the meaning of this, here I will just post the last self optimized code post, other versions as well as please download from my resources: http://download.csdn.net/detail/chenqiai0/5233058
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <stdbool.h> #define
Filenumbers 3//indicates the number of files #define Filenamenum 256//indicates that the file name is the maximum 256 int cal (char filename[256]);
void *thread_function (void *arg); int wordcount=0;//three files total words int count[3]={0,0,0};//Three files The initial values are 0 char filenames[filenumbers][filenamenum]={"file1",
"File2", "File3"};
pthread_mutex_t filemutex;//defines a mutex variable int main () {int i=0;
int flag;//is used to judge whether the operation is correct pthread_t thread[3];
int count1=0,count2=0,count3=0;
/* Mutual-exclusion lock initialization/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*) &file
Names[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 ("Total number of words:%d\n", wordcount);
return 0;
int cal (Char filename[256]) {bool start;
int count=0;//is used to record the number of words 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 is used to indicate the beginning of a word, start=1 indicates that there is no while (feof (FP) ==0)//feof (FP) ==0 indicates that it has not yet been to the end of the file {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);I believe we all better way, please leave a message.