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

q7.4 Fix the errors in the code (in C) //This program is supposed to scan 5...
q7.4 Fix the errors in the code (in C) //This program is supposed to scan 5 ints from the user //Using those 5 ints, it should construct a linked list of 5 elements //Then it prints the elements of the list using the PrintList function #include <stdio.h> struct Node{ int data; Node* next; }; int main(void){ struct Node first = {0, 0}; struct Node* second = {0, 0}; Node third = {0, 0}; struct Node fourth = {0, 0}; struct...
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;...
q7.1 Fix the errors in the code (in C) //This program should read a string from...
q7.1 Fix the errors in the code (in C) //This program should read a string from the user and print it using a character pointer //The program is setup to use pointer offset notation to get each character of the string #include <stdio.h> #include <string.h> int main(void){ char s[1]; scanf(" %c", s); char *cPtr = s[1]; int i=0; while(1){ printf("%c", cPtr+i); i++; } printf("\n"); }
C++ code won't run. Fix? //========================================================== #include <conio.h> // For function getch() #include <cstdlib> // For...
C++ code won't run. Fix? //========================================================== #include <conio.h> // For function getch() #include <cstdlib> // For several general-purpose functions #include <fstream> // For file handling #include <iomanip> // For formatted output #include <iostream> // For cin, cout, and system #include <string> // For string data type using namespace std; // So "std::cout" may be abbreviated to "cout" //Converting hexadecimal to binary int main() {    char binarynum[65], hexa[17];    //Using long int because it has greater capacity    long int...
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,...
In c++: Code Challenge Consider the following code: struct ListNode { int value; struct ListNode *next;...
In c++: Code Challenge Consider the following code: struct ListNode { int value; struct ListNode *next; }; ListNode *head; // List head pointer Assume that a linked list has been created and head points to the first node. Write code that traverses the list displaying the contents of each node’s value member Now write the code that destroys the linked list
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...
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.
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT