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...
Python 3 Fix the code. It is not saving the data into the xls file Code:...
Python 3 Fix the code. It is not saving the data into the xls file Code: import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook from tkinter import messagebox from datetime import datetime window = tk.Tk() window.title("daily logs") window.grid_columnconfigure(1,weight=1) window.grid_rowconfigure(1,weight=1) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Working product").grid(row=4, sticky="W", pady=20, padx=20) #Working product label tk.Label(window, text="Failed...
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...
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.
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
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...
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number...
Can anyone fix this code? The code isn't rounding the answer to the nearest whole number like 2.345 should be 2 and 2.546 should be 3 but the round() function isn't working as expected. The round() function is rounding 2.546 to 2 which is incorrect since 4 and below should be rounded to 2 and 5 and above should be rounded to 3. Here is the code: #importing xlwt library to write into xls import xlwt from xlwt import Workbook...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT