Question: Part 2: Pthread Mutex Observation (5 points) A file named pthread-data-sharing-mutex-os-call.cpp has been provided to you in the same project. Compile the program and execute

Part 2: Pthread Mutex Observation (5 points)

A file named pthread-data-sharing-mutex-os-call.cpp has been provided to you in the same project.

Compile the program and execute it several times, at least 10. Make sure to pay close attention to the output that the program produces.

Create a Word or Google Docs document.

In this document, answer the following questions about the programs behavior:

What does it do?

What output does it produce?

Examine the program code carefully. Is the program functioning correctly?

If you do not think that the program is working correctly, describe why?

Include one screenshot of the programs output. Your choice.

Code to be analyzed is as follows:

#include #include #include

#define TOTAL_THREADS 4

int count; pthread_mutex_t the_mutex; // phread mutex variable

void* myFunction(void* arg) { int actual_arg = *((int*) arg); for(unsigned int i = 0; i < 10; ++i) { // TODO: // Use a Pthread mutex to control // access to the critical region.

// Beginning of the critical region count++; std::cout << "Thread #" << actual_arg << " count = " << count << std::endl; // Random wait - This code is just to ensure that the threads // show data sharing problems int max = rand() % 100000; for (int x = 0; x < max; x++); // End of random wait code // End of the critical region } pthread_exit(NULL); }

int main() { int rc[TOTAL_THREADS]; pthread_t ids[TOTAL_THREADS]; int args[TOTAL_THREADS]; // TODO: Initialize the pthread mutex here count = 0; for(unsigned int i = 0; i < TOTAL_THREADS; ++i) { args[i] = i; rc[i] = pthread_create(&ids[i], NULL, myFunction, (void*) &args[i]); } for(unsigned int i = 0; i < TOTAL_THREADS; ++i) { pthread_join(ids[i], NULL); } std::cout << "Final count = " << count << std::endl; pthread_exit(NULL); }

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!