Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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

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

    1. Answer the following questions about the programs behavior:

      1. What does this program do?

      2. What output does it produce?

      3. Examine the program code carefully. Is the program functioning correctly? What is wrong with it?

#include #include #include

#define TOTAL_THREADS 4

int count; pthread_mutex_t the_mutex; // phread mutex variable - initialize here if using the initializer macro

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;

// End of the critical region // TODO: // Relinquish access to the Pthread mutex // since critical region is complete.

// 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 } pthread_exit(NULL); }

int main() { int rc[TOTAL_THREADS]; pthread_t ids[TOTAL_THREADS]; int args[TOTAL_THREADS]; // TODO: Initialize the pthread mutex here if using the initialization function. 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

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_2

Step: 3

blur-text-image_step3

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 Instant Reference

Authors: Gruber, Martin Gruber

2nd Edition

ISBN: 0782125395, 9780782125399

More Books

Students also viewed these Databases questions