Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C (for unix/linux programming), twordcount1.c to modify: twordcount 1 . c use

ID: 643476 • Letter: I

Question

In C (for unix/linux programming),

twordcount1.c to modify:

twordcount 1 . c uses three threads: the original thrad and the two threads to count the words, but the original thread doesn?t do much. Write a version of the program in which the original thread counts the words in the first file and creates a second thread to count the number of words in the second file. Ask yourself: is this any faster? Is it a better design? A sample run would display the total word counts of two files. Usage: twd1 file 1 file2

Explanation / Answer

#include "stdio.h" #include "pthread.h" #include "ctype.h" #include "stdlib.h" void* count_words( void* ); int total_words; int main( int ac, char* av[] ) { pthread_t t1; // one threads if ( ac != 3 ) { printf( "usage: %s file1 file2 " ,av[0] ); exit(1); } total_words = 0; char* filename = av[1]; FILE* fp; int c, prevc = ''; if ( ( fp = fopen( filename, "r" ) ) != NULL ) { while( ( c = getc( fp ) ) != EOF ) { if ( !isalnum( c ) && isalnum( prevc ) ) total_words++; prevc = c; } fclose( fp ); pthread_create( &t1, NULL, count_words, (void*)av[2] ); pthread_join( t1, NULL ); return 0; } void* count_words( void* f ) { char* filename = ( char* )f; FILE* fp; int c, prevc = ''; if ( ( fp = fopen( filename, "r" ) ) != NULL ) { while( ( c = getc( fp ) ) != EOF ) { if ( !isalnum( c ) && isalnum( prevc ) ) total_words++; prevc = c; } fclose( fp ); } else perror( filename ); return NULL; }