Question

In: Computer Science

int compare_and_swap(int *value, int expected, int new_value) { int temp = *value; if ( *value ==...

int compare_and_swap(int *value, int expected, int new_value) {
int temp = *value;
if ( *value == expected ) *value = new_value;
return temp;
}

Suppose that a machine has an atomic compare_and_swap() instruction that sets the value to new_value only if the expression ( *value == expected ) is true. Regardless, compare_and_swap() always returns the original value of the variable value.

Using the compare__and_swap() instruction, give a mutual-exclusion solution to the n-process critical section problem. Use only the shared variable lock.

int lock = 0; /* shared variable - initialized to 0 */
do {
/*Fill this section*/
} while ( true );

Please answer me. I'll give you a thumbs up!

Solutions

Expert Solution


int compare_and_swap(int *value, int expected, int new_value) {
    int temp = *value;
    if ( *value == expected ) 
        *value = new_value;
    return temp;
}

int lock=0; /* lock is a shared variable - initialized to 0 */

do{
   //main logic that will forces mutual-exclusion amongst processes
   while (compare_and_swap(&lock, 0, 1) != 0) ;//it's a trap!!
   
   /* This is our critical section area in which a process will access or modify a shared resource*/
   
   /* now after a process completes its task in critical section then it will make the value of shared variable lock as 0 so that other process can go into 
      critical section */
   
   lock = 0;
   /* remainder code */
}
while (true);

Code Explainations:

As we know that a critical section is that area of our code in which we access or modify the shared resources.

So a critical section must be implemented in such a way that it should support the mutual-exclusion machenism

Now we can implement the critical section in either or two way : one is using Software Solution and other is by using Hardware Solution.

We can implement critical section using Peterson's Solution as a software solution or can use Semaphores to implement it.

We can implement Hardware Solution using compare_and_swap() instruction.

A compare_and_swap() instruction will be an atomic machine instruction.

Working of compare_and_swap() instruction:

Here we are mainly focused to achieve Mutual Exclusion to the n-processes means at a time only one process is allowed to enter into the critical section.

for that we have implemented the compare_and_swap() function which will simply swap the shared variable lock based on some criteria.

Here initially our lock is set to 0.

Let's say Process P1 wants to go into the critical section,so first it will have to call compare_and_swap() instruction just to make sure the mutual exclusion amongst the processes ensures.

Now as we called compare_and_swap(int *value,int expected,int new_value),

we have provided:

&lock--->*value,0---->expected,1---->new_value

now compare_and_swap() will work as follow:

  1. temp will hold the value of lock.
  2. we will check if the value of lock is equal to expected value or not if it is.then make assign the new_value to the value and finally return the temp.
  3. but if it is not we just simply return the value of temp.

Here when the first process P1 has called compare_and_swap(int *value,int expected,int new_value),in while loop it return 0 as that time lock was set as 0.

now while loop condition become false and P1 enters into the critical section.

now let's assume that another process P2 wants to go in critical section by context-switching the P1,

so P2 also have to call compare_and_swap(int *value,int expected,int new_value), but this time compare_and_swap(int *value,int expected,int new_value), will return 1 as the value of lock was set 1 by P1.

So now P2 has to wait until P1 again make the lock as 0.

Once P1 completed it's execution it will make lock as 0 and now P2 can go into critical section by making the value of lock as 1 so that no other process can come in critical section while P2 doing it's taks there.

So we can see here for any number of processes say P1,P2,P3.....Pn are there at a time only one process is allowed to go into critical section.

All other processes has to perform busy-waiting.

So this solution will ensure us the Mutual-Exclution amongst n-processes.


Related Solutions

Consider the following program written in C syntax: void swap(int a, int b) { int temp;...
Consider the following program written in C syntax: void swap(int a, int b) { int temp; temp = a; a = b; b = temp;} void main() { int value = 2, list[5] = {1, 3, 5, 7, 9}; swap(value, list[0]); swap(list[0], list[1]); swap(value, list[value]); } For each of the following parameter-passing methods, what are all of the values of the variables value and list after each of the three calls to swap? Passed by value Passed by reference Passed...
Use pseudocode to describe an algorithm for the procedure: int[][] find_pairs( int array[], int value ).
Use pseudocode to describe an algorithm for the procedure: int[][] find_pairs( int array[], int value ). Given a sorted array of distinct integers and a single integer value, find all pairs of indexes in the list whose product is equal to the value. Return the index pairs on the same row of a two-dimensional array. Note, m will be the number of rows and total number of pairs found, while 2 will be the number of columns along every row...
public static int punishOrMercy(char direction, int reward) Output: int which will be the value of zero...
public static int punishOrMercy(char direction, int reward) Output: int which will be the value of zero or the initial reward. Functionality: After the result of the reward function is stored, this function should be called. The goal of this function is to help the robot in case it faced a lot of damage in the current step. However, this function will help the robot only if the robot’s reward was negative and the direction that the user inputted was up....
int value = 1; do { if (value % 2 == 0) cout << value <<...
int value = 1; do { if (value % 2 == 0) cout << value << " "; value = value + 1; } while (value % 7 != 0); cout << "\n" << value; What will be displayed?
Temp A                                         &nb
Temp A                                                            Temp B Mean = 101.52                                                Mean = 98.48 Standard deviation = 1.05                              Standard deviation = 0.65 a. Calculate a 95% tolerance interval for Temp A. Round each value to 2 decimal places b. Calculate a 95% tolerance interval for Temp B. Round each value to 2 decimal places c. Is there any overlap between the tolerance intervals you calculated in parts (a) and (c) (i.e do they cover any of the same region on a number line –...
At a temp below room temp but with all components as gases, the decomposition of iodine...
At a temp below room temp but with all components as gases, the decomposition of iodine monochloride, ICl, to iodine and chlorine, is 1.4*10^-5 2ICl (g)----> I2 (g) + Cl2 (g) If a sealed vessel has [ICl]=1.87 M, and no iodine or chlorine. What are the equilibrium cocentrations?
Write a Haskell function combine :: Int -> Int -> Int -> Int with the following...
Write a Haskell function combine :: Int -> Int -> Int -> Int with the following behavior: • When x, y, and z all correspond to digit values (i.e., integers between 0 and 9, inclusive), combine x y z returns the integer given by the sequence of digits x y z. (That is, x is treated as the digit in the hundreds place, y is treated as the digit in the tens place, and z is treated as the digit...
string getStyle() ; int getNumOfBedRooms() ; int getNumOfBathRooms(); int getNumOfCarsGarage(); int getYearBuilt(); int getFinishedSquareFootage() ; double...
string getStyle() ; int getNumOfBedRooms() ; int getNumOfBathRooms(); int getNumOfCarsGarage(); int getYearBuilt(); int getFinishedSquareFootage() ; double getPrice(double p) ; double getTax(double t) ; void print() ; houseType(); houseType(string s, int numOfBeds, int numOfBaths, int numOfCars, int yBuilt, int squareFootage, double p, double t); private: string style; int numOfBedrooms; int numOfBathrooms; int numOfCarsGarage; int yearBuilt; int finishedSquareFootage; double price; double tax; }; Questions a.Write the definition of the member function set so that private members are set accordingy to the parameters....
Expected Value of X
A couple decides to have 3 children. If none of the 3 is a girl, they will try again; and if they still don’t get a girl, they will try once more. If the random variable X denotes the number of children the couple will have following this scheme, then what is the expected value of X?
Date - month: int - day: int - year: int +Date() +Date(month: int, day: int, year:...
Date - month: int - day: int - year: int +Date() +Date(month: int, day: int, year: int) +setDate(month: int, day: int, year: int): void -setDay(day: int): void -setMonth(month: int): void -setYear(year: int): void +getMonth():int +getDay():int +getYear():int +isLeapYear(): boolean +determineSeason(): string +printDate():void Create the class Constructor with no arguments sets the date to be January 1, 1900 Constructor with arguments CALLS THE SET FUNCTIONS to set the Month, then set the Year, and then set the Day - IN THAT ORDER...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT