Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

It seems like these don\'t lock properly, How can i fix them? #include <stdio.h>

ID: 3914756 • Letter: I

Question

It seems like these don't lock properly, How can i fix them?

#include <stdio.h>

//#include "stdafx.h"

#include <iostream>

#include <thread>

#include <queue>

#include <mutex>

using namespace std;

queue<int> patients;

int seats = 0;

//mutex to ensure that only one patient is consulted at one time

mutex doct;

//mutex to ensure that the seats are occupied one after the other

mutex sts;

void doctorState()

{

while (true)

{

if (!patients.empty())

{

cout << " Patient " << patients.front() << " is getting treatment.";

patients.pop();

break;

}

else

{

cout << " Doctor is sleeping.";

break;

}

}

}

void patientHandler(int i)

{

while (true)

{

if (doct.try_lock())

{

sts.lock();

seats--;

sts.unlock();

doctorState();

doct.unlock();

break;

}

else if (seats < 3)

{

sts.lock();

cout << " Patient " << i << " waiting. Seats Occupied. " << ++seats <<" seats full.";

sts.unlock();

}

else

{

cout << " Patient " << i << " drinking coffee for " << i << " seconds.";

this_thread::sleep_for(std::chrono::seconds(1));

}

}

}

int main()

{

printf(" ");

thread p[10];

for (int i = 0; i < 10; i++)

{

p[i] = std::thread(patientHandler, i);

patients.push(i);

}

thread doct(doctorState);

for(int i = 0; i < 10; i++)

{

p[i].join();

}

doct.join();

printf(" ");

}

Explanation / Answer

that's error due to unstable versions of C++ you should run the application like this

g++ filename.cpp -std=c++11

It executed the full code for me.

If you are using Code Blocks IDE you set it as goto Project then Build Options then Compiler Settings and then Compiler Flags and check the Second Option

In case of Dev C++ follow as:

Menu -> Project -> Project Options -> Compiler -> Code Generation -> Language standard (-std). And finally set: GNU C++11?.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote