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’.
[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)
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.
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...
zyDE 9.16.1: Dice game Craps. Modify the playerWins() method to update highCredits. The current solution does...
zyDE 9.16.1: Dice game Craps. Modify the playerWins() method to update highCredits. The current solution does not work correctly. Increment numTurns in the most appropriate method. The current solution does not work correctly. As a result, the percentage of wins calculation attempts to divide by zero. // Simulates a dice game called Craps import java.util.Random; import java.text.DecimalFormat; import java.util.Scanner; public class Craps { // Game statistics private int diceTotal; private int credits; private int numTurns; private int numWins; private int...
Modify HW#1. C++ use,Write a multithreaded program that tests your solution to HW#1. You will create...
Modify HW#1. C++ use,Write a multithreaded program that tests your solution to HW#1. You will create several threads – for example, 100 – and each thread will request a pid, sleep for a random period of time, and then release the pid. (Sleeping for a random period approximates the typical pid usage in which a pid is assigned to a new process, the process executes and terminates, and the pid is released on the process’ termination).On UNIX and Linux systems,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT