Answered step by step
Verified Expert Solution
Link Copied!

Question

00
1 Approved Answer

Given the following program, what, if anything should be done? #include #include #include #include using namespace std; mutex mtx 1 , mtx 2 ; void

Given the following program, what, if anything should be done?
#include
#include
#include
#include
using namespace std;
mutex mtx1,mtx2;
void john(){
for (auto i: {1,2,3}){
mtx1.lock();
this_thread::sleep_for(chrono::milliseconds(301));
mtx2.lock();
cout << "John has the locks" << endl;
mtx2.unlock();
mtx1.unlock();
}
}
void jane(){
for (auto i: {1,2,3}){
mtx2.lock();
this_thread::sleep_for(chrono::milliseconds(300));
mtx1.lock();
cout << "Jane has the locks" << endl;
mtx1.unlock();
mtx2.unlock();
}
}
int main(){
auto t1= thread(john);
auto t2= thread(jane);
t1.join();
t2.join();
}
Group of answer choices
void jane(){
for (auto i: {1,2,3}){
mtx1.lock();
cout << "Jane has the lock" << endl;
mtx1.unlock();
}
}
// NEVER USE TWO MUTEXES together, so remove mtx2
void jane(){
for (auto i: {1,2,3}){
lock (mtx1, mtx2);
cout << "Jane has the locks" << endl;
}
}
//(Because lock() automatically unlocks when it goes out of scope.)
void jane(){
for (auto i: {1,2,3}){
mtx1.lock(mtx2);
cout << "Jane has the locks" << endl;
mtx2.unlock();
mtx1.unlock();
}
}
//(Because mtx1 will not lock until it locks mtx2)
void jane(){
for (auto i: {1,2,3}){
lock (mtx1, mtx2);
cout << "Jane has the locks" << endl;
mtx2.unlock();
mtx1.unlock();
}
}
//(Because lock() does not acquire the locks until it can get both.)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions