Question: Operating Systems: I need to edit a C programs to make them work. We are using threads, DO NOT EDIT THE CODE, just add what

Operating Systems: I need to edit a C programs to make them work. We are using threads, DO NOT EDIT THE CODE, just add what is needed in the areas that have comments there (where is says TODO).

Calculator: Write a program that can read the file numbers.txt with one thread and add all number with multiple threads (one thread per line). The final answer should be 1000. HINT: Keep in mind that if you pass a value by reference it will be shared with all the threads, consider saving a copy of each line in separate address locations. ///////////////////////////////// calculator.c ////////////////////////////////////////////////////

#include // printf()

#include // atoi(), exit(), ...

#include // strtok(), strcmp(), ...

#include // pthread types and functions

#define MAX_LINE_LENGTH 100

#define NUM_THREADS 4

int sum = 0;

pthread_mutex_t sum_mutex; // Mutex variables help keep the threads synchronized

void *add_line_numbers(void *arg) {

char *line = (char *) arg;

int line_sum = 0;

// TODO Break down the line and add every number

// What does pthread_mutex_lock/unlock do?

// It ensures the section between this lock/unlock statements can only be executed by 1 process,

// if another needs access it must wait until the first runs the unlock statement

pthread_mutex_lock(&sum_mutex);

// TODO Add the result of the line to the global sum

pthread_mutex_unlock(&sum_mutex);

pthread_exit(NULL);

}

int main() {

FILE *file;

char line[MAX_LINE_LENGTH];

pthread_t threads[NUM_THREADS];

pthread_mutex_init(&sum_mutex, NULL);

file = fopen("numbers.txt", "r");

if (file == NULL) {

printf("Error: cannot open file ");

exit(EXIT_FAILURE);

}

int line_count = 0;

while (fgets(line, MAX_LINE_LENGTH, file) != NULL) {

// TODO Create your threads with the given line (remember sharing address locations is not good with threads)

line_count++;

}

int i;

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

// TODO Wait until all threads finish reading the lines

}

printf("Sum of all numbers in the file is %d ", sum);

fclose(file);

pthread_mutex_destroy(&sum_mutex); // destroys the mutex variable

pthread_exit(NULL); // destroys main thread

}

/////////////////////////////// numbers.txt ///////////////////////////////// 1 2 3 4 5 6 7 8 9 10 11 12 13 15 16 17 178 23 34 45 56 34 56 78 34 56 7 98 6 54 86 4 12

Make in bold the areas that you edited so I know what you did to fix the code. Thank you. And no, I can't use comments because this website is trash, so just do the code correctly the first time please.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!