Question

In: Computer Science

Explain the multithreading issue in the following c++ code and fix it. (consider options such as...

Explain the multithreading issue in the following c++ code and fix it. (consider options such as mutex lock). 


#include <iostream>
#include <thread>
#include <string>
#include <unistd.h>

using namespace std;    
static int tickets = 32;
static int sale = 0;
class Seller {
public:
        void Main()
        {
                for (;;)
                {
                        if(tickets <= 0){
                                cout << "In Seller[" << ID <<"] sold out"<< endl;
                                break;
                        }else{
                                tickets--;
                                sale++;
                                usleep(1);
                                cout << "In Seller[" << ID <<"]"<<sale<< endl;
                        }
                }
        }
        int ID;
};
 
int main()
{
        Seller st1;
        st1.ID = 1;
    Seller st2;
        st2.ID = 2;
        Seller st3;
        st3.ID = 3;
        Seller st4;
        st4.ID = 4;
        Seller st5;
        st5.ID = 5;
        
        thread th1(&Seller::Main, &st1);
        thread th2(&Seller::Main, &st2);        
        thread th3(&Seller::Main, &st3);        
        thread th4(&Seller::Main, &st4);
        thread th5(&Seller::Main, &st5);
    
        th1.join();
        th2.join();
    th3.join();
    th4.join();
    th5.join();
    
        return 0;
}

Solutions

Expert Solution

If there is no such locking condition involved in the above program all the threads seller 1 , 2, 3, 4, 5 we will begin parallely executing the main program and two or more seller might be selling same ticket to the customer which causes violation . If run the above program without any mutex lock output would look like

In Seller[4]11                                                                                                                                   

In Seller[3]11                                                                                                                                   

In Seller[2]11                                                                                                                                   

In Seller[5]16                                                                                                                                   

In Seller[4]17                                                                                                                                   

In Seller[3]18                                                                                                                                   

In Seller[2]19                                                                                                                                   

In Seller[1]20                                                                                                                                   

In Seller[5]21                                                                                                                                   

In Seller[4]22                                                                                                                                   

In Seller[3]23                                                                                                                                   

In Seller[2]24                                                                                                                                   

In Seller[1]25                                                                                                                                   

In Seller[5]26                                                                                                                                   

In Seller[4]27                                                                                                                                   

In Seller[3]28                                                                                                                                   

In Seller[2]29                                                                                                                                   

In Seller[1]30                                                                                                                                   

In Seller[5]31                                                                                                                                   

In Seller[4]32                                                                                                                                   

In Seller[4] sold out                                                                                                                            

In Seller[5]32                                                                                                                                   

In Seller[5] sold out                                                                                                                            

In Seller[3]32                                                                                                                                   

In Seller[3] sold out                                                                                                                            

In Seller[2]32                                                                                                                                   

In Seller[2] sold out                                                                                                                            

In Seller[1]32                                                                                                                                   

In Seller[1] sold out  

As you can see in the above output ticket 11 is sold by sellers 4 , 3, 2 which is not aceptable. Now let us try to modify the above program by using mutex lock and unlock. Locking should be done before code where the race condition begins and after the code finishes unlock should be done.

Below is the following code and updated part of code is in bold. Here we try to keep lock variable before booking process i.e., before if statement and unlock after else statement completion. And we are keeping unlock again after for loop because if tickets are sold out loop is breaked and execution goes to end of for loop without passing through else block. By doing so other sellers can also get to know that tickets have been sold out .

#include <iostream>

#include <thread>

#include <mutex>

#include <string>

#include <unistd.h>

using namespace std;   

static int tickets = 32;

static int sale = 0;

std::mutex mtx;

class Seller {

public:

void Main()

{

for (;;)

{

mtx.lock();

if(tickets <= 0){

cout << "In Seller[" << ID <<"] sold out"<< endl;

break;

}else{

tickets--;

sale++;

usleep(1);

cout << "In Seller[" << ID <<"]"<<sale<< endl;

  

}

mtx.unlock();

}

mtx.unlock();

}

int ID;

};

int main()

{

Seller st1;

st1.ID = 1;

Seller st2;

st2.ID = 2;

Seller st3;

st3.ID = 3;

Seller st4;

st4.ID = 4;

Seller st5;

st5.ID = 5;

  

thread th1(&Seller::Main, &st1);

thread th2(&Seller::Main, &st2);   

thread th3(&Seller::Main, &st3);   

thread th4(&Seller::Main, &st4);

thread th5(&Seller::Main, &st5);

  

th1.join();

th2.join();

th3.join();

th4.join();

th5.join();

  

return 0;

}

Below is screenshot of output of above code for proof of work.


Related Solutions

Need to fix this code for tc -tac-toe game .. see the code below and fix...
Need to fix this code for tc -tac-toe game .. see the code below and fix it #include <iostream> using namespace std; void display_board(); void player_turn(); bool gameover (); char turn ; bool draw = false; char board [3][3] = { {'1', '2', '3'}, { '4', '5', '6'}, { '7', '8', '9'}}; int main() { cout << " Lets play Tc- Tac- toe game " <<endl ; cout << " Player 1 [X] ----- player 2 [0] " <<endl <<endl;...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The...
C++ Bank Account Error Fix, full code. I am using Dev-C++ to Compile and Execute. The project is below, I have supplied the code and I'm getting an error in SavingsAccount.h file. 17   5   C:\Users\adam.brunell\Documents\Classes\C++\Week4\SavingsAccount.h   [Error] 'SavingsAccount::SavingsAccount(std::string, double, double)' is protected A.Assume i.SavingsAccount: Assume an Interest Rate of 0.03 ii.HighInterestSavings: Assume an Interest Rate of 0.05, Minimum Balance = $2500 iii.NoServiceChargeChecking: Assume an Interest Rate = 0.02, Minimum of Balance = $1000 iv.ServiceChargeChecking – Assume account service charge = $10,...
Can you fix the code and comment the fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39 at...
Can you fix the code and comment the fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39 at CaesarCipher.encrypt(CaesarCipher.java:28) at CaesarCipher.main(CaesarCipher.java:52) public class CaesarCipher{     char[] encoder = new char[52];     char[] decoder = new char[52];      public CaesarCipher(int rotation)      {        for(int k=0 ; k < 26 ; k++)        {            encoder[k] = (char) ('A' + (k + rotation) % 26);            decoder[k] = (char) ('A' + (k - rotation + 26) % 26);        }        for(int j...
fix this code in python and show me the output. do not change the code import...
fix this code in python and show me the output. do not change the code import random #variables and constants MAX_ROLLS = 5 MAX_DICE_VAL = 6 #declare a list of roll types ROLLS_TYPES = [ "Junk" , "Pair" , "3 of a kind" , "5 of a kind" ] #set this to the value MAX_ROLLS pdice = [0,0,0,0,0] cdice = [0,0,0,0,0] #set this to the value MAX_DICE_VAL pdice = [0,0,0,0,0,0] cdice = [0,0,0,0,0,0] #INPUT - get the dice rolls i...
What is wrong with the following code? Give two effective ways to fix it. 1 import...
What is wrong with the following code? Give two effective ways to fix it. 1 import javax.swing.*; 2 import java.awt.event.*; 3 4 public class H2ClassJ extends JFrame { 5    public static final long serialVersionUID = 22; 6 7 public H2ClassJ () { 8      addMouseListener (new MouseListener () { 9    public void mouseClicked (MouseEvent e) {} 10     }); 11   } // end constructor 12 13 } // end class H2ClassJ
Explain how multithreading can complicate the implementation of the singleton pattern and explain how to resolve...
Explain how multithreading can complicate the implementation of the singleton pattern and explain how to resolve this complication.
Consider the following C code: (10 marks) // write a MIPS instruction to initialize s0 to...
Consider the following C code: // write a MIPS instruction to initialize s0 to 6 t0 = ((s03 - 93)2 + s0 ) << 2 t1 = t0 / 4 Q2.1: Write a MIPS program that performs the operation of the above C program. Q2.2: What is the value of $t0 and $t1 after running your MIPS program (write your answer in a comment at the end of the code). Submit your answer to Q2 in a file named A2_Q2.asm
Javascript. Consider the following code fragment, that is supposed to compute the pixel value let c...
Javascript. Consider the following code fragment, that is supposed to compute the pixel value let c = image.getPixel(x, y); const m1 = (c[0] + c[1] + c[2]) / 3; c = image.getPixel(x + 1, y); const m2 = (c[0] + c[1] + c[2]) / 3; image.setPixel(x, y, [m1 - m2, m1 - m2, m1 - m2]); Give three pairs of pixel values (x, y) = [?, ?, ?] and (x+1, y) = [?, ?, ?] in the input image, for...
Fix the following java code package running; public class Run {    public double distance; //in...
Fix the following java code package running; public class Run {    public double distance; //in kms    public int time; //in seconds    public Run prev;    public Run next;    //DO NOT MODIFY - Parameterized constructor    public Run(double d, int t) {        distance = Math.max(0, d);        time = Math.max(1, t);    }       //DO NOT MODIFY - Copy Constructor to create an instance copy    //NOTE: Only the data section should be...
Find and fix the compile time bugs in the code at the end of this section....
Find and fix the compile time bugs in the code at the end of this section. Compile time bugs show as errors when you compile, but the Visual Studio IDE also gives you visual clues in the form of red squiggly underlines, as shown here. This assignment is meant to test your attention to detail and strengthen your debugging skills. Here is the code. // Week 4 Assignment-1 // Description: Compile time errors //---------------------------------- //**begin #include files************ #include <iostream> //...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT