[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <pthread. h>
# Include <stdbool. h>
# Define filenumbers 3 // number of files
# Define filenamenum 256 // indicates the maximum file name is 256
Int cal (char filename [1, 256]);
Void * thread_function (void * arg );
Int wordcount = 0; // The total number of words in the three files
Int count [3] = {0, 0}; // The initial values of the number of words in the three files are 0.
Char filenames [filenumbers] [filenamenum] = {"file1", "file2", "file3 "};
Pthread_mutex_t fileMutex; // defines a mutex variable.
Int main ()
{Int I = 0;
Int flag; // used to determine whether the operation is correct
Pthread_t thread [3];
// Int count1 = 0, count2 = 0, count3 = 0;
/* Mutex 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 *) & 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 ("Total Number of words: % d \ n", wordcount );
Return 0;
}
Int cal (char filename [1, 256])
{
Bool start;
Int count = 0; // 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 indicates the start of a word, and start = 1 indicates no
While (feof (fp) = 0) // feof (fp) = 0 indicates that the end of the file is not reached.
{
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 );
}