Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Need help with the following questions: 1)Why is there no mutex variable in this program? 2)Do you think letting the program create threads unbounded is

Need help with the following questions:

1)Why is there no mutex variable in this program?

2)Do you think letting the program create threads unbounded is efficient? Why or why not?

Program:

#include // printf(), fgets()

#include // exit(), malloc(), free()

#include // strtok(), strcmp()

#include // pthread types and functions

#define MAX_LINE_LENGTH 255

#define MAX_DICTIONARY_SIZE 202412

char dictionary[MAX_DICTIONARY_SIZE][MAX_LINE_LENGTH];

int dictionary_size = 0;

pthread_mutex_t dictionary_mutex;

void *check_word(void *arg) {

char *word = (char *) arg;

int i;

for (i = 0; i < dictionary_size; i++) {

if (strcmp(dictionary[i], word) == 0) {

printf("%s is spelled correctly. ", word);

pthread_exit(NULL);

}

}

printf("%s is spelled incorrectly. ", word);

pthread_exit(NULL);

}

int main() {

char line[MAX_LINE_LENGTH];

pthread_t threads[MAX_DICTIONARY_SIZE];

FILE *dictionary_file = fopen("dictionary.txt", "r");

if (dictionary_file == NULL) {

printf("Error: cannot open dictionary file ");

exit(EXIT_FAILURE);

}

while (fgets(dictionary[dictionary_size], MAX_LINE_LENGTH, dictionary_file) != NULL) {

dictionary[dictionary_size][strlen(dictionary[dictionary_size]) - 1] = '\0';

dictionary_size++;

}

fclose(dictionary_file);

printf("Enter a line of text: ");

while (fgets(line, MAX_LINE_LENGTH, stdin) != NULL && line[0] != '.') {

char *word = strtok(line, " ");

while (word != NULL) {

pthread_create(&threads[dictionary_size], NULL, check_word, (void *) word);

dictionary_size++;

word = strtok(NULL, " ");

}

}

for (int i = 0; i < dictionary_size; i++) {

pthread_join(threads[i], NULL);

}

pthread_exit(NULL);

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

SQL Server Query Performance Tuning

Authors: Sajal Dam, Grant Fritchey

4th Edition

1430267429, 9781430267423

More Books

Students also viewed these Databases questions