El Dj El Dj - 2 months ago 10
C++ Question

How do I implement no hold and wait to prevent a deadlock

I have written an intentionally deadlocked code which has 2 locks and the way I'm deadlocking the program is like this:

void ThreadAtWork1(){
m1.lock();
cout<<"Thread 1 has been called\n";
m2.lock();
m1.unlock();
m2.unlock();
}

void ThreatAtWork2(){
m2.lock();
cout<<"Thread 2 has been called\n";
m1.lock();
m2.unlock();
m1.unlock();

}


How can I implement a no 'hold and wait' solution to stop the program from deadlocking? I know I can just re-order the locks but that won't solve the no hold and wait solution.

My main function:

int main(int argc, const char * argv[]) {

thread t1(ThreadAtWork1);
thread t2(ThreatAtWork2);

t1.join();
t2.join();

cout<<"\nMain exited...\n";

return 0;
}


Thanks.

Answer Source

I did figure it out a while ago but forgot to update this post. Below is how I went about it and got 100 on it.

//for hold and wait, just don't allocate the resource if a thread asks for it. Just wait and execute the other one

//t1-> request W. requires W
//t2-> has W
//t1 checks if W is free. wait
//t2 executes. Releases W
//t1 executes

//basically, if all locks are free, execute, else not.