Question

In: Computer Science

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

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

PROGRAM:

#include <iostream>
#include <pthread.h>
#include <stdlib.h>


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


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 << std::endl;
pthread_exit(NULL);
}

Solutions

Expert Solution

Hello! :)

Since the turn variable is initialized with 0, which is the value of actual_arg of the first thread, it gets to execute the part after line 22 first but the second thread is blocked at line 22 because its actual_arg value is 1. After execution, if we toggle the value of turn (assign the not of turn to turn), the first thread gets blocked at line 22 whereas the second thread gets to execute the part after line 22 since turn becomes 1 now. Similarly, after the second thread is done executing and toggling turn, it gets blocked and the first thread gets to execute. This alteration continues till both threads are done executing.

Here's the code with the modification in line 43 (marked with the comment: // ADDED):

#include <iostream>
#include <pthread.h>
#include <stdlib.h>


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


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.
  
  
turn = !turn;                                                               // ADDED


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

Here's a screenshot of a demo run:

Hope this helps! :)


Related Solutions

Write a program to simulate the Distributed Mutual Exclusion in ‘C’.
Write a program to simulate the Distributed Mutual Exclusion in ‘C’.
Please prove the correctness of the following extended compare_and_wait program in terms of mutual exclusion, progress,...
Please prove the correctness of the following extended compare_and_wait program in terms of mutual exclusion, progress, and bounded waiting. please show it in the in terms of mutual exclusion, progress, and bounded waiting.aspects thankyou while (true) { waiting[i] = true; key = 1; while (waiting[i] && key == 1) key = compare_and_swap(&lock,0,1); waiting[i] = false;    // critical section j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall...
[PYTHON] Modify the examaverages.py program included with this assignment so it will also compute the overall average test grade. E.g if there are 3 test each student must take and the user enters the following set of test scores for the two students…: 30, 40, 50 for the first student 50, 60, 70 for the second student …then program will print the average for each student (i.e. 40 for the first student and 60 for the second student – the...
Question Four Explain Peterson’s solution for critical-section problem and show that mutual exclusion is preserved with...
Question Four Explain Peterson’s solution for critical-section problem and show that mutual exclusion is preserved with Peterson’s solution. (Assume there are only two processes P0 and P1)
Modify the code below to implement the program that will sum up 1000 numbers using 5...
Modify the code below to implement the program that will sum up 1000 numbers using 5 threads. 1st thread will sum up numbers from 1-200 2nd thread will sum up numbers from 201 - 400 ... 5th thread will sum up numbers from 801 - 1000 Make main thread wait for other threads to finish execution and sum up all the results. Display the total to the user. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define N_OF_THREADS 4 void * print(void...
Using Java create a program that does the following: Modify the LinkedList1 class by adding sort()...
Using Java create a program that does the following: Modify the LinkedList1 class by adding sort() and reverse() methods. The reverse method reverses the order of the elements in the list, and the sort method rearranges the elements in the list so they are sorted in alphabetical order. Do not use recursion to implement either of these operations. Extend the graphical interface in the LinkedList1Demo class to support sort and reverse commands, and use it to test the new methods....
Implement a program in C++ that does the following: Ask the user and read at least...
Implement a program in C++ that does the following: Ask the user and read at least 10 numbers as input from the keyboard and stores them in a an array Displays the array of numbers on the screen (as is, before sorting) Sorts those numbers in the array using Selection Sort Algorithm Displays the array of numbers on the screen (AFTER sorting)
Budda-Bing Manufacturing is planning to implement a major plant-modernization program to improve its competitive position. Included...
Budda-Bing Manufacturing is planning to implement a major plant-modernization program to improve its competitive position. Included will be construction of a state-of-the-art manufacturing facility that will cost $400,000 in 2019 and is expected to lower the company's variable cost per tonne of steel. Tony and Pauli, experienced budged analysts, have been charged with preparing a forecast of the firm's 2019 financial position assuming construction of the proposed new facility. They plan to use the 2018 financial statements presented below along...
Please show solution and comments for this data structure using java.​ Implement a program in Java...
Please show solution and comments for this data structure using java.​ Implement a program in Java to convert an infix expression that includes (, ), +, -, *,     and / to postfix expression. For simplicity, your program will read from standard input (until the user enters the symbol “=”) an infix expression of single lower case and the operators +, -, /, *, and ( ), and output a postfix expression.
Implement a program as an object using a class (abstract data type) in C++ that does...
Implement a program as an object using a class (abstract data type) in C++ that does the following: 1) reads the firstName, lastName and 3 test scores of at least five students. 2) calculate student test score totals, average, letter grade for each student. 3) Display the results in a table format showing firstName, lastName, test1, test2, test3, total, average, letterGrade, of all the students. 3 files .h, .cpp, main.cpp create an object that can hold records. must get records...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT