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

implement a program to count the frequency of words in a text file. the text fil

ID: 3722830 • Letter: I

Question

implement a program to count the frequency of words in a text file. the text file is partitioned into N segments. Each segment is processed by a separate thread that outputs the intermediate frequency count for its segment. The main process waits until the threads complete; then it computes the consolidated word-frequency data based on the individual threads' output. *written in C*

Explanation / Answer

#include #include #include #include #include pthread_mutex_t mtx; // used by each of the three threads to prevent other threads from accessing global_sum during their additions int global_sum = 0; typedef struct{ char* word; char* filename; }MyStruct; void *count(void*str) { MyStruct *struc; struc = (MyStruct*)str; const char *myfile = struc->filename; FILE *f; int count=0, j; char buf[50], read[100]; // myfile[strlen(myfile)-1]=''; if(!(f=fopen(myfile,"rt"))){ printf("Wrong file name"); } else printf("File opened successfully "); for(j=0; fgets(read, 10, f)!=NULL; j++){ if (strcmp(read[j],struc->word)==0) count++; } printf("the no of words is: %d ",count); pthread_mutex_lock(&mtx); // lock the mutex, to prevent other threads from accessing global_sum global_sum += count; // add thread's count result to global_sum pthread_mutex_unlock(&mtx); // unlock the mutex, to allow other threads to access the variable } int main(int argc, char* argv[]) { int i; MyStruct str; pthread_mutex_init(&mtx, NULL); // initialize mutex pthread_t threads[argc-1]; // declare threads array for (i=0;i