Question: 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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!