Modify the included program to implement the strict alternation solution to achieve mutual exclusion. It does...

70.2K

Verified Solution

Question

Programming

Modify the included program to implement the strict alternationsolution to achieve mutual exclusion. It does not matter whetherThread 0 goes first or Thread 1, but it is important that thethread strictly alternate.

PROGRAM:

#include
#include
#include


int count;
int turn = 0; // Shared variable used to implement strictalternation


void* myFunction(void* arg)
{
   int actual_arg = *((int*) arg);
  
   for(unsigned int i = 0; i < 10; ++i) {
  
// TODO:
// Make sure that the thread waits for its turn
// before it enters the critical region.
//
// HINT: The thread ID is stored in actual_arg
  
while(turn != actual_arg);
  
  
  
// Beginning of the critical region
  
count++;
std::cout << \"Thread #\" << actual_arg << \" count= \" << count << std::endl;
  
// End of the critical region
  
  
  
// TODO:
// Make sure that the other thread gets a turn
//
// HINT: There are only two threads: 0 and 1
// You can use the C++ NOT operator (!)
// to toggle back and forth.
  
  


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


// HINT: It is not necessary to make any changes in main()
int main()
{
int rc[2];
pthread_t ids[2];
int args[2];
  
count = 0;
for(unsigned int i = 0; i < 2; ++i) {
args[i] = i;
rc[i] = pthread_create(&ids[i], NULL, myFunction, (void*)&args[i]);
}
  
for(unsigned int i = 0; i < 2; ++i) {
pthread_join(ids[i], NULL);
}
  
std::cout << \"Final count = \" << count <pthread_exit(NULL);
}

Answer & Explanation Solved by verified expert
4.5 Ratings (843 Votes)
Hello Since the turn variable is initialized with 0 which is thevalue of actualarg of the first thread it gets to execute thepart after line 22 first but the second thread is blocked at line22 because its    See Answer
Get Answers to Unlimited Questions

Join us to gain access to millions of questions and expert answers. Enjoy exclusive benefits tailored just for you!

Membership Benefits:
  • Unlimited Question Access with detailed Answers
  • Zin AI - 3 Million Words
  • 10 Dall-E 3 Images
  • 20 Plot Generations
  • Conversation with Dialogue Memory
  • No Ads, Ever!
  • Access to Our Best AI Platform: Flex AI - Your personal assistant for all your inquiries!
Become a Member

Other questions asked by students